std::type_info::hash_code
来自 cppreference.cn
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; // note that we're storing pointer to type 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 中移除) |
检查对象是否引用相同的类型 (公共成员函数) |
类型的实现定义名称 (公共成员函数) |