Namespaces
Variants

std:: type_index

From cppreference.net
Utilities library
定義済みヘッダー <typeindex>
class type_index ;
(C++11以降)

type_index クラスは、連想コンテナおよび非順序連想コンテナのインデックスとして使用できる std::type_info オブジェクトのラッパークラスです。 type_info オブジェクトとの関係はポインタを通じて維持されるため、 type_index CopyConstructible かつ CopyAssignable です。

目次

翻訳内容: - "Contents" → "目次" - C++関連の用語("Member functions"、"Helper classes"、"Example"、"See also")は原文のまま保持 - HTMLタグ、属性、構造は完全に保持 - 番号付けや書式は変更なし

メンバー関数

オブジェクトを構築する
(public member function)
(destructor)
(implicitly declared)
type_index オブジェクトを破棄する
(public member function)
operator=
(implicitly declared)
type_index オブジェクトを代入する
(public member function)
基となる std::type_index オブジェクトを比較する
(public member function)
ハッシュコードを返す
(public member function)
実装定義の型名を返す、
基となる type_info オブジェクトに関連付けられた
(public member function)

ヘルパークラス

std::type_index のハッシュサポート
(クラステンプレートの特殊化)

以下のプログラムは、効率的な型-値マッピングの例です。

#include <iostream>
#include <memory>
#include <string>
#include <typeindex>
#include <typeinfo>
#include <unordered_map>
struct A
{
    virtual ~A() {}
};
struct B : A {};
struct C : A {};
int main()
{
    std::unordered_map<std::type_index, std::string> type_names;
    type_names[std::type_index(typeid(int))] = "int";
    type_names[std::type_index(typeid(double))] = "double";
    type_names[std::type_index(typeid(A))] = "A";
    type_names[std::type_index(typeid(B))] = "B";
    type_names[std::type_index(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[std::type_index(typeid(i))] << '\n';
    std::cout << "d is " << type_names[std::type_index(typeid(d))] << '\n';
    std::cout << "a is " << type_names[std::type_index(typeid(a))] << '\n';
    std::cout << "*b is " << type_names[std::type_index(typeid(*b))] << '\n';
    std::cout << "*c is " << type_names[std::type_index(typeid(*c))] << '\n';
}

出力:

i is int
d is double
a is A
*b is B
*c is C

関連項目

型の情報を含む、typeid演算子によって返されるクラス
(クラス)