我的程序中有一种情况,我需要从字符串转换为各种类型,显然结果只能是一种类型.所以我选择创建一个union并称之为变体,如下:
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.
};
Run Code Online (Sandbox Code Playgroud)
我使用它如下:
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;
}
Run Code Online (Sandbox Code Playgroud)
然后我在这里使用该功能:
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++;
}
Run Code Online (Sandbox Code Playgroud)
问题是,如果我使用它,struct那么它的用户将能够在其中粘贴多个值,而这实际上并不意味着发生.但似乎我也不能使用联盟,因为我无法将boost::gregorian::date对象放入其中.如果我有办法可以使用,有人可以建议union吗?