在线文档教程
C++
应用 | Utilities

std::type_info::hash_code

性病::类型[医]信息::散列[医]代码

size_t hash_code() const;(since C++11)

返回一个未指定的值,该值与type_info对象引用相同的类型。没有其他保证。例如,不同类型可能返回相同的值。该值还可以在同一程序的调用之间进行更改。

参数

%280%29

返回值

某些值,对于相同类型的值是相同的。

下面的程序是一个有效的类型值映射的示例,而无需使用std::type_index...

二次

#include <iostream> #include <typeinfo> #include <unordered_map> #include <string> #include <functional> #include <memory> 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

二次

另见

operator==operator!=checks whether the objects refer to the same type (public member function)
nameimplementation defined name of the type (public member function)

© cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

http://en.cppreference.com/w/cpp/type/type[医]信息/散列[医]代码