Is it possible to define (in a simple way, possibly re-using std container) an "associative std::tuple
", or said in other words a "variadiac std::map
".
Something like this (this interface is just to explain, other possible interfaces are welcome):
AssociativeTuple<std::string> at; // std:string is the key type
at.insert<float>("my_float", 3.14); // 1.
at.insert<int>("my_int", 42);
at.insert<bool>("my_bool", true);
at.insert<int>("xyz", 0);
at.insert<std::string>("my_string", "hello world!");
assert(get(at, "my_float") == 3.14); // 2.
assert(get(at, "my_int") == 42);
assert(at["my_string"] == "hello world!"); // 3.
assert(std::is_same<at.type_of("my_float")::type, float>) // 4.
for (auto it : at) { std::cout << it.first << " = " << it.second; } // 5.
Other desirable constraints:
- The set of values/keys are known only at running time. But at compile time the user know the relation between (the type of the values) and keys. For example the user know at compiling time that
"my_float"
will be afloat
. To say in another way the set possible of keys is fixed and the type of the value corresponding to a key is known at compile time. What is not known at compiling time is "if" a key will be inserted inside the container. Of course the value of the map value is not known at compiling time. - Access performance,
get
should be fast - The user don't have to remember the type associated to a key
My real problem is just with value of float
/int
/bool
type (and what I am doing is to store in everything in a std::map<std::string, float>
and converting to int
when necessary), but a general solution is desirable. In my real case the keys are always std::string
.