Combining in C ++ and custom design objects

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; // Compiler complains this object has a user-defined ctor and/or non-default ctor. }; 

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 ?

+4
source share
3 answers

Use boost :: variant or boost :: any. Union is not a solution when you need to combine non-POD.

+5
source

Instead of gregorian :: date, save the greg_ymd structure and use the year_month_day () method to convert the date to ymd.

+1
source

You say you cannot put boost :: gregorian :: date in a union because it is a non-POD type? C ++ 0x relaxes this limitation. If you get gcc 4.6 and build it with -std = C ++ 0x, you can put it in a union. See here: http://en.wikipedia.org/wiki/C%2B%2B0x#Unrestricted_unions .

0
source

All Articles