std::type_info::hash_code
ja.cppreference.net より
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
関連項目
|
(removed in C++20)
|
オブジェクトが同じ型を参照しているかどうかをチェックする
(public member function) |
|
実装定義の型名
(public member function) |