If you know in advance what all kinds of values map
is going to hold, then use boost::variant
. Or else, use boost::any
. With boost::any
, you could later add entries with any type of value to the map.
Example code with boost::variant
:
Creating a map:
typedef boost::variant<std::string, std::map<int, int>, int> MyVariantType;
std::map<std::string, MyVariantType> hash;
Adding entries:
hash["somedata"] = "Hello, yo, me being a simple string";
std::map<int, int> temp;
temp[6] = 5;
temp[13] = 9;
hash["somearray"] = temp;
hash["simple_data_again"] = 198792;
Retrieving values:
std::string s = boost::get<std::string>(hash["somedata"]);
int i = boost::get<int>(hash["simple_data_again"]);
As pointed out by @Matthieu M in the comments, the key-type of the map can be a boost::variant
. This becomes possible because boost::variant
provides a default operator<
implementation providing the types within all provide it.
Example code with boost::any
:
Creating a map:
std::map<std::string, boost::any> hash;
Adding entries:
hash["somedata"] = "Hello, yo, me being a simple string";
std::map<int, int> temp;
temp[6] = 5;
temp[13] = 9;
hash["somearray"] = temp;
hash["simple_data_again"] = 198792;
Retrieving values:
std::string s = boost::any_cast<std::string>(hash["somedata"]);
int i = boost::any_cast<int>(hash["simple_data_again"]);
Thus, with help of boost::any
the value-type in your map can be dynamic (sort of). The key-type is still static, and I don't know of any way how to make it dynamic.
A word of advice:
C++ is a statically typed language. The idioms like the one in your post which are used quite often in dynamic language don't fit well with the C++ language. Going against the grain of a language is a recipe for pain.
Therefore I'd advise you not to try to emulate the idioms from your favorite dynamic languages in C++. Instead learn the C++ ways to do things, and try to apply them to your specific problem.
References: