Does C++11 provide hashing functions for std::type_info?
I'm still working on a good solution to my One-Of-A-Type Container Problem -- and upon reflection I think it would be nice to be able to just use something like a std::map<std::type_info, boost::any>
. Unfortunately, std::type_info
does not define an operator<
, and I think it'd be unreasonable for it to define one.
However, it does seem reasonable to define a hash function for it, because you could simply use the singleton address of the std::type_info
object as a reasonable "hash". Therefore, you'd be able to put a std::type_info
into a std::unordered_map
as the key.
Does C++11 provide such a hash function? Would using the memory address of开发者_Python百科 the std::type_info
singleton be a bad hash strategy?
You could also use type_index, it safely holds a pointer to a type_info, it's copyable, comparable and a hash function is provided for standard containers.
The fact that type_info
is not less-than comparable isn't as much a problem for using it as a map key as the fact that type_info
is non-copyable. :-)
In C++03, type_info
has a before()
member function that provides an ordering of type_info
objects.
In C++11, type_info
has a hash_code()
member function (C++11 §18.7.1/7):
size_t hash_code() const throw();
Returns: an unspecified value, except that within a single execution of the program, it shall return the same value for any two
type_info
objects which compare equal.Remark: an implementation should return different values for two
type_info
objects which do not compare equal.
type_info
objects resulting from the typeid
operator exist until the end of the program, so it is safe to use a type_info*
as a map key. However, to the best of my knowledge, there is no guarantee that if you apply typeid
to two objects of the same type you will get two references to the same type_info
object.
If you do use type_info*
as a map key, I'd use a custom comparator that dereferences the pointers and compares the type_info
objects themselves (using the aforementioned before()
or hash_code()
for ordering).
精彩评论