首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::type_index

Defined in header <typeindex>

class type_index;

(since C++11)

type_index类的包装器类。std::type_info对象,可用作关联和无序关联容器中的索引。与...的关系type_info对象是通过指针维护的。type_indexCopyConstructibleCopyAssignable...

成员函数

(constructor)

constructs the object (public member function)

(destructor) (implicitly declared)

destroys the type_index object (public member function)

operator= (implicitly declared)

assigns a type_index object (public member function)

operator==operator!=operator<operator<=operator>operator>=

compares the underlying std::type_info objects (public member function)

hash_code

returns hashed code (public member function)

name

returns implementation defined name of the type, associated with underlying type_info object (public member function)

帮助者类

std::hash<std::type_index> (C++11)

hash support for std::type_index (class template specialization)

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

二次

代码语言:javascript
复制
#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;
 
    // 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';
}

二次

产出:

二次

代码语言:javascript
复制
i is int
d is double
a is A
b is B
c is C

二次

另见

type_info

contains some type's information, generated by the implementation. This is the class returned by the typeid operator. (class)

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券