Namespaces
Variants

std::type_info:: hash_code

From cppreference.net
Utilities library
std:: size_t hash_code ( ) const noexcept ;
(C++11以降)

同じ型を参照するすべての std::type_info オブジェクトについて、それらの hash code が同じになるような、未規定の値(ここでは hash code と表記)を返します。

その他の保証は一切ありません: std::type_info オブジェクトが異なる型を参照している場合でも、同じ hash code を持つ可能性があります(ただし標準では実装がこれを可能な限り避けることを推奨しています)。また、同じ型に対する hash code は、同一プログラムの異なる実行間で変更される可能性があります。

目次

パラメータ

(なし)

戻り値

同じ型を参照するすべての 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

関連項目

(removed in C++20)
オブジェクトが同じ型を参照しているかどうかをチェックする
(public member function)
実装定義の型名
(public member function)