Does C ++ 11 provide hash functions for std :: type_info?

I am still working on a good solution to my problem with a One-Of-Type container - and after thinking it would be nice to be able to just use something like std::map<std::type_info, boost::any> . Unfortunately, std::type_info does not define operator< , and I think it would be unwise to define it.

However, it seems reasonable to define a hash function for it, because you can simply use the single address of the std::type_info as a reasonable "hash". So you can put std::type_info in std::unordered_map as a key.

Does C ++ 11 provide such a hash function? Will using the std::type_info singleton memory address as a bad hash strategy?

+7
c ++ unordered-map c ++ 11 rtti
source share
2 answers

The fact that type_info no less than comparable is not so much as to use it as a map key as the fact that type_info not copied. type_info

In C ++ 03, type_info has a member function before() that provides ordering of type_info objects.

In C ++ 11, type_info has a hash_code() member hash_code() (C ++ 11 Β§18.7.1 / 7):

 size_t hash_code() const throw(); 

Returns: an undefined value, except that during one execution of the program it must return the same value for any two type_info objects that are compared equal.

Note: the implementation must return different values ​​for two type_info objects that are not compared with equals.

type_info objects that are the result of the typeid operator exist until the end of the program, so it is safe to use type_info* as the map key. However, as far as I know, 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 use type_info* as the map key, I would use a custom comparator that separates the pointers and compares the type_info objects type_info (using the aforementioned before() or hash_code() for ordering).

+9
source share

You can also use type_index , it reliably holds a pointer to type_info, it can be copied, mapped and a hash function for standard containers.

+10
source share

All Articles