名前空間
変種
操作

std::type_index

From cppreference.com
< cpp‎ | types
 
 
ユーティリティライブラリ
言語サポート
型のサポート (基本型、RTTI)
ライブラリ機能検査マクロ (C++20)
プログラムユーティリティ
可変引数関数
コルーチンサポート (C++20)
契約サポート (C++26)
三方比較
(C++20)
(C++20)(C++20)(C++20)  
(C++20)(C++20)(C++20)

汎用ユーティリティ
関係演算子 (C++20で非推奨)
 
 
 
ヘッダ <typeindex> で定義
class type_index;
(C++11以降)

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

目次

[編集] メンバ関数

オブジェクトを構築する
(public member function) [編集]
(デストラクタ)
(暗黙的に宣言)
type_index オブジェクトを破棄します
(public member function)
operator=
(暗黙的に宣言)
type_index オブジェクトを代入します
(public member function)
基になる std::type_info オブジェクトを比較します
(public member function) [編集]
ハッシュコードを返します
(public member function) [編集]
基になる type_info オブジェクトに関連付けられた、型の実装定義名を返します。
基になる 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演算子によって返されるクラス
(クラス) [編集]
English 日本語 中文(简体) 中文(繁體)