名稱空間
變體
操作

std::type_info::hash_code

來自 cppreference.com
< cpp‎ | 型別‎ | 型別資訊
 
 
 
 
 
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 中移除)
檢查物件是否引用相同的型別
(公共成員函式) [編輯]
型別的實現定義名稱
(公共成員函式) [編輯]