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

孤者浪人 提交于 2019-12-06 23:47:39

问题


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 the std::type_info singleton be a bad hash strategy?


回答1:


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).




回答2:


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.



来源:https://stackoverflow.com/questions/3552135/does-c11-provide-hashing-functions-for-stdtype-info

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!