我正在尝试实现一个定制的变体类型,它使用联合存储各种不同类型的数据。在字段type_id
中,我计划存储联合中存储的数据的类型。该联合包含非平凡成员。这是我目前的实现:
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;
};
};
我尝试按照以下方式创建MyVariant
的实例:
MyVariant v;
我收到了错误信息:调用MyVariant的隐式删除默认构造函数。所以,我尝试手动实现构造函数如下:
MyVariant() : type_id{t_int}, as_int{0} {}
这给了我一个类似的错误消息:尝试使用已删除的函数。 接下来,我尝试实现以下构造函数:
MyVariant(int value) : type_id{t_int}, as_int{value} {}
然后按照以下方式构建我的实例:
MyVariant v{123};
相同的错误信息: 尝试使用已删除的函数。
我还开始实现一个复制构造函数,代码如下。但是,当然这并不能解决编译器错误。
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>();
// TODO: copy values from other
break;
}
}
我正在使用Xcode和Apple LLVM 6.1编译器。
主要问题是:为什么我会得到当前的编译器错误?我该如何修改我的代码才能使其编译通过?
此外还有一个问题:我的构造函数和拷贝构造函数实现是否正确?