I have a situation in my program where I need to do some conversion from strings to different types, and, obviously, the result can be only one type. So I decided to create a union and called it a variant:
union variant { int v_int; float v_float; double v_double; long v_long; boost::gregorian::date v_date;
I use 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 this 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 struct , then users from it can insert more than one value into it, and this really should not happen. But it looks like I can't use a join either, since I can't put a boost::gregorian::date object in it. Can anyone advise if there is a way to use union ?
source share