std::type_index_C++中文网

type_index 类是一个围绕 std::type_info 的包装类,它可用作关联与无序关联容器的索引。它与 type_info 对象的关系通过一个指针维系,故而 type_index 可复制构造 (CopyConstructible) 可复制赋值 (CopyAssignable)

成员函数

构造对象
(公开成员函数)

(析构函数)

(隐式声明)

销毁 type_index 对象
(公开成员函数)

operator=

(隐式声明)

type_index 对象赋值
(公开成员函数)
比较底层 std::type_info 对象
(公开成员函数)
返回哈希码
(公开成员函数)
返回关联到底层 type_info 对象的实现定义名称
(公开成员函数)

辅助类

示例

下面的程序是一个有效的类型-值映射的示例。

#include <iostream>
#include <typeinfo>
#include <typeindex>
#include <unordered_map>
#include <string>
#include <memory>
 
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;
 
    // 注意我们正在存储指向类型 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

参阅