我希望通过
std::map
使用type_index
来存储不同数据类型的信息,从cppreference.com学到的。
例如:
#include <typeindex>
class A{};
class B{};
int main()
{
map<type_index, string> info{
{type_index[typeid(A)], "Information for class A."},
{type_index[typeid(B)], "Information for class B."}
};
}
typeid()
将返回一个结构体 type_info
。
但我了解到
type_info.hash_code()
可能不是唯一的。不同类型可能有相同的hash_code
。
我想知道type_index
是否是独一无二的?
是的,
std::type_index
是独一无二的。据说它的工作方式就好像它有一个指向std::type_info
的指针。
尽管您可以获得相同类型的不同指针,但它们不会直接进行比较。相反,使用
std::type_info::before()
。
如果跨共享库边界获得相同类型的看似不同的
std::type_index
对象(==
返回 false),请确保使用 __attribute__((__visibility__("default")))
标记有问题的类型。我们在 ARM Mac 上遇到了枚举(所有事物)的问题。