Using templates as keys in a std::map

If you didn't disabled RTTI explicitly, refer to nogard's answer. Standard type id is garanteed to be unique for a whole program across DLL. This is not true for the address of a function.

What I usually do is this:

template<typename T>
void type_id(){}

using type_id_t = void(*)();

Then, I use it like this:

std::map<type_id_t, Node> nodes;

nodes[type_id<AType>] = Node{...};
nodes[type_id<BType>] = Node{...};

Of course, this can be enhanced with variable template from C++14.


Sorry, I just re-read the question and I understand it better.

What you want is std::any, but it's C++17 only. You can use boost::any instead.

It will look like this:

std::map<std::any, Node> nodes;

nodes.emplace("string as key", Node{});
nodes.emplace(23, Node{});

It should work as long as the map can somehow order instances of std::any. If not, you can use hash map instead:

std::unordered_map<std::any, Node> nodes;

Then it will work as long as the map can hash an any.


I think for this purpose it's much easier to use std::type_info for the types:

std::map<std::type_info, std::string> m;
m[typeid(int)] = "integer";

But this really depends on what you want to achieve, it's still unclear to me. Hope that helps