C++ associative array with arbitrary types for values

Posted by Gerald Kaszuba on Stack Overflow See other posts from Stack Overflow or by Gerald Kaszuba
Published on 2008-12-29T10:52:22Z Indexed on 2011/01/17 4:53 UTC
Read the original article Hit count: 169

Filed under:
|
|
|

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?

© Stack Overflow or respective owner

Related posts about c++

Related posts about arrays