gpt4 book ai didi

c++ - C++ 中的 union 和非默认可构造对象

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:40:19 24 4
gpt4 key购买 nike

我的程序中有一种情况,我需要进行一些从字符串到各种类型的转换,显然结果只能是一种类型。所以我选择创建一个 union 并将其命名为 variant,如下所示:

union variant
{
int v_int;
float v_float;
double v_double;
long v_long;
boost::gregorian::date v_date; // Compiler complains this object has a user-defined ctor and/or non-default ctor.
};

我是这样使用的:

bool Convert(const std::string& str, variant& var)
{
StringConversion conv;

if (conv.Convert(str, var.v_int))
return true;
else if (conv.Convert(str, var.v_long))
return true;
else if (conv.Convert(str, var.v_float))
return true;
else if (conv.Convert(str, var.v_double))
return true;
else if (conv.Convert(str, var.v_date))
return true;
else
return false;
}

然后我在这里使用该函数:

while (attrib_iterator != v_attributes.end())  //Iterate attributes of an XML Node
{
//Go through all attributes & insert into qsevalues map
Values v; // Struct with a string & boost::any
v.key = attrib_iterator->key;
///value needs to be converted to its proper type.
v.value = attrib_iterator->value;
variant var;
bool isConverted = Convert(attrib_iterator->value, var); //convert to a type, not just a string
nodesmap.insert(std::pair<std::string, Values>(nodename, v));
attrib_iterator++;
}

问题是,如果我使用 struct,那么它的用户将能够在其中添加一个以上的值,而这确实是不应该发生的。但似乎我也不能使用 union ,因为我不能将 boost::gregorian::date 对象放入其中。有没有人可以建议我是否可以使用 union

最佳答案

使用 boost::variant 或 boost::any。当您必须合并非 POD 时, union 不是解决方案。

关于c++ - C++ 中的 union 和非默认可构造对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4277220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com