I have a situation in my program where I need to do some conversion from strings to various types and obviously the outcome can only be ever one type. So I opted to create a union
and called it variant, as such:
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.
};
I am using it as follows:
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;
}
and then I use that function here:
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++;
}
The problem is that if I use a struct
then users of it will be able to stick more then one value in it, and that really is not meant to happen. But it seems I cannot use a union either, as I cannot put the boost::gregorian::date
object in it. Can anybody advice if there is a way I could use a union
?