C ++ 11是否为std :: type_info提供了哈希函数? [英] Does C++11 provide hashing functions for std::type_info?
问题描述
我仍然在为单一类型的容器问题 - 和反射我认为能够只是使用像一个 std :: map< std :: type_info,boost :: any>
。不幸的是, 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.
然而,为它定义一个哈希函数似乎是合理的,因为你可以简单地使用 std的单例地址: :type_info
对象作为合理的散列。因此,您可以将 std :: type_info
放入 std :: unordered_map
中作为键。
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.
C ++ 11提供这样的哈希函数吗?将使用 std :: type_info
单例的内存地址是一个坏的哈希策略?
Does C++11 provide such a hash function? Would using the memory address of the std::type_info
singleton be a bad hash strategy?
推荐答案
事实上, type_info
不小于可比较不是使用它作为映射键的问题,因为 type_info
是不可复制的。 : - )
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. :-)
在C ++ 03中, type_info
有一个 before / code>成员函数提供
type_info
对象的排序。
In C++03, type_info
has a before()
member function that provides an ordering of type_info
objects.
type_info
具有 hash_code()
成员函数(C ++ 11§18.7.1/ 7):
In C++11, type_info
has a hash_code()
member function (C++11 §18.7.1/7):
size_t hash_code() const throw();
返回:未指定的值,程序,它应该返回任何两个 type_info
对象相同的值。比较等于。
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.
对于两个 type_info
对象,实现应该返回不同的值,这些对象不会相等。
Remark: an implementation should return different values for two type_info
objects which do not compare equal.
$从 typeid
运算符产生的b $ b
type_info
对象存在,直到程序结束,可以安全地使用 type_info *
作为映射键。但是,据我所知,不能保证,如果你应用 typeid
到同一类型的两个对象,你会得到两个引用相同 type_info
对象。
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.
如果你使用 type_info *
作为映射键,我将使用一个自定义比较器,并且比较 type_info
对象本身(使用上述 before()
或 hash_code / code>订购)。
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).
这篇关于C ++ 11是否为std :: type_info提供了哈希函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!