Namespaces
Variants

std::type_info:: hash_code

From cppreference.net
Utilities library
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 中移除)
检查对象是否引用相同类型
(公开成员函数)
实现定义的类型名称
(公开成员函数)