I am trying to implement a custom variant type that uses a union to store data of various types. In the type_id field type_id I plan to save that type of data stored in the union. The union contains nontrivial members. Here is my current implementation:
struct MyVariant { enum { t_invalid, t_string, t_int, t_double, t_ptr, t_dictionary } type_id; union { int as_int; double as_double; std::string as_string; std::unique_ptr<int> as_ptr; std::map<int, double> as_dictionary; }; };
I am trying to create an instance of MyVariant as shown below:
MyVariant v;
I get an error: the implicitly deleted default constructor MyVariant is called. So, I tried to implement the constructor manually, as shown below:
MyVariant() : type_id{t_int}, as_int{0} {}
This gives me a similar error message: trying to use a remote function. Then I tried to implement the following constructor:
MyVariant(int value) : type_id{t_int}, as_int{value} {}
and build my example as follows:
MyVariant v{123};
=> same error message: attempt to delete a remote function.
I also started implementing the copy constructor, it looks like this. However, of course, this does not help with compiler errors.
MyVariant::MyVariant(const MyVariant& other) { type_id = other.type_id; switch (type_id) { case t_invalid: break; case t_string: new (&as_string) std::string(); as_string = other.as_string; break; case t_int: as_int = other.as_int; break; case t_double: as_double = other.as_double; break; case t_ptr: new (&as_ptr) std::unique_ptr<int>(nullptr); as_ptr = std::make_unique<int>(*other.as_ptr); break; case t_dictionary: new (&as_dictionary) std::map<int, double>();
I am using Xcode and Apple LLVM 6.1 as a compiler.
The main question is: why do I get the compiler errors that I get, and how do I change the code so that it compiles?
Additional question: am I correct with my implementations for the copy constructor and constructor?
c ++ constructor c ++ 11 unions c ++ 14
j00hi
source share