std::type_index
来自cppreference.com
<tbody>
</tbody>
| 在标头 <typeindex> 定义
|
||
class type_index; |
(C++11 起) | |
type_index 类是一个围绕 std::type_info 的包装类,它可用作关联容器与无序关联容器的索引。它与 type_info 对象的关系通过一个指针维系,故而 type_index 为可复制构造 (CopyConstructible) 且为可复制赋值 (CopyAssignable) 。
成员函数
| 构造对象 (公开成员函数) | |
(析构函数) (隐式声明) |
销毁 type_index 对象 (公开成员函数) |
operator= (隐式声明) |
对 type_index 对象赋值 (公开成员函数) |
| 比较底层 std::type_index 对象 (公开成员函数) | |
| 返回散列码 (公开成员函数) | |
| 返回与底层 type_info 对象关联的类型的实现定义名称 (公开成员函数) |
辅助类
(C++11) |
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;
// 注意我们正在存储指向类型 A 的指针
std::unique_ptr<A> b(new B);
std::unique_ptr<A> c(new C);
std::cout << "i 是 " << type_names[std::type_index(typeid(i))] << '\n';
std::cout << "d 是 " << type_names[std::type_index(typeid(d))] << '\n';
std::cout << "a 是 " << type_names[std::type_index(typeid(a))] << '\n';
std::cout << "*b 是 " << type_names[std::type_index(typeid(*b))] << '\n';
std::cout << "*c 是 " << type_names[std::type_index(typeid(*c))] << '\n';
}
输出:
i 是 int
d 是 double
a 是 A
*b 是 B
*c 是 C
参阅
| 包含某个类型的信息,typeid 运算符所返回的类 (类) |