std::type_index
来自 zh.cppreference.net
| 定义于头文件 <typeindex>
|
||
class type_index;
|
(C++11 起) | |
类 type_index 是围绕一个 std::type_info 对象的包装类,可用作关联容器和无序关联容器中的索引。与 type_info 对象的关系通过指针维护,因此 type_index 是 可复制构造 (CopyConstructible) 和 可复制赋值 (CopyAssignable) 的。
成员函数
|
构造对象
(公开成员函数) |
|
|
(destructor)
(implicitly declared)
|
销毁
type_index
对象
(公开成员函数) |
|
operator=
(implicitly declared)
|
赋值
type_index
对象
(公开成员函数) |
|
(removed in C++20)
(C++20)
|
比较底层
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 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 运算符返回的类
(类) |