std::type_info::hash_code
From cppreference.com
| 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で削除) |
オブジェクトが同じ型を参照しているかを調べる (public メンバ関数) |
| 型の実装定義名 (public member function) |