What is the best way to have an associative array with arbitrary value types for each key in C++?
Currently my plan is to create a ‘value’ class with member variables of the types I will be expecting. For example:
class Value { int iValue; Value(int v) { iValue = v; } std::string sValue; Value(std::string v) { sValue = v; } SomeClass *cValue; Value(SomeClass *v) { cValue = c; } }; std::map<std::string, Value> table;
A downside with this is you have to know the type when accessing the ‘Value’. i.e.:
table['something'] = Value(5); SomeClass *s = table['something'].cValue; // broken pointer
Also the more types that are put in Value, the more bloated the array will be.
Any better suggestions?
boost::variant seems exactly what you are looking for.