std::type_info::hash_code
来自 zh.cppreference.net
std::size_t hash_code() const noexcept;
|
(C++11 起) | |
返回一个未指定的值(此处称为哈希码),使得对于所有引用相同类型的std::type_info对象,它们的哈希码相同。
不提供其他保证:引用不同类型的std::type_info对象可能具有相同的哈希码(尽管标准建议实现应尽可能避免这种情况),并且同一类型的哈希码在同一程序的不同调用之间可能会发生变化。
参数
(无)
返回值
一个对于所有引用同一类型的 std::type_info 对象都相同的值。
示例
以下程序是一个不使用 std::type_index 的高效类型-值映射示例。
运行此代码
#include <functional> #include <iostream> #include <memory> #include <string> #include <typeinfo> #include <unordered_map> struct A { virtual ~A() {} }; struct B : A {}; struct C : A {}; using TypeInfoRef = std::reference_wrapper<const std::type_info>; struct Hasher { std::size_t operator()(TypeInfoRef code) const { return code.get().hash_code(); } }; struct EqualTo { bool operator()(TypeInfoRef lhs, TypeInfoRef rhs) const { return lhs.get() == rhs.get(); } }; int main() { std::unordered_map<TypeInfoRef, std::string, Hasher, EqualTo> type_names; type_names[typeid(int)] = "int"; type_names[typeid(double)] = "double"; type_names[typeid(A)] = "A"; type_names[typeid(B)] = "B"; type_names[typeid(C)] = "C"; int i; double d; A a; // 注意我们存储的是指向类型A的指针 std::unique_ptr<A> b(new B); std::unique_ptr<A> c(new C); std::cout << "i is " << type_names[typeid(i)] << '\n'; std::cout << "d is " << type_names[typeid(d)] << '\n'; std::cout << "a is " << type_names[typeid(a)] << '\n'; std::cout << "*b is " << type_names[typeid(*b)] << '\n'; std::cout << "*c is " << type_names[typeid(*c)] << '\n'; }
输出:
i is int d is double a is A *b is B *c is C
参见
|
(C++20 中移除)
|
检查对象是否引用相同类型
(公开成员函数) |
|
实现定义的类型名称
(公开成员函数) |