std::type_info::hash_code
来自cppreference.com
<tbody>
</tbody>
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 是 " << type_names[typeid(i)] << '\n';
std::cout << "d 是 " << type_names[typeid(d)] << '\n';
std::cout << "a 是 " << type_names[typeid(a)] << '\n';
std::cout << "*b 是 " << type_names[typeid(*b)] << '\n';
std::cout << "*c 是 " << type_names[typeid(*c)] << '\n';
}
输出:
i 是 int
d 是 double
a 是 A
*b 是 B
*c 是 C
参阅
(C++20 移除) |
检查对象是否指代相同类型 (公开成员函数) |
| 类型的实现定义名称 (公开成员函数) |