C++ std::type_index的用法(附带实例)
C++ 的 std::type_index 类位于 <typeindex> 头文件中,封装了对 std::type_info 对象的引用,提供了一种方式来安全地存储和使用类型信息的索引。
std::type_index 主要作为关联容器如(std::map 或 std::unordered_map)的键值使用,因为直接使用 std::type_info 是不允许的(type_info 对象没有公开的默认构造函数,且拷贝和赋值操作都被禁止)。
std::type_index 的主要功能和用途如下:
下面的程序演示了 std::type_index 的用法:
std::type_index 主要作为关联容器如(std::map 或 std::unordered_map)的键值使用,因为直接使用 std::type_info 是不允许的(type_info 对象没有公开的默认构造函数,且拷贝和赋值操作都被禁止)。
std::type_index 的主要功能和用途如下:
- 类型安全的索引:std::type_index 提供了一种方法来比较和存储运行时类型信息,使其在容器中的处理更为简便和安全。这对于实现如工厂模式等设计模式中,需要根据类型动态创建对象的场景非常有用;
- 容器中的类型管理:使用 std::type_index 可以将类型信息作为键存储在任何标准关联容器中,如 std::map<std::type_index, std::unique_ptr<Base>>,便于管理一系列通过基类接口派生的对象实例。
- 类型比较:与 std::type_info 直接比较不同,std::type_index 提供了必要的比较运算符,允许在标准容器中对类型进行排序或查找操作。
下面的程序演示了 std::type_index 的用法:
#include <typeindex> #include <typeinfo> #include <unordered_map> #include <iostream> #include <memory> class Base { public: virtual ~Base() {} virtual void doWork() = 0; }; class Derived1 : public Base { public: void doWork() override { std::cout << "Derived1 working." << std::endl; } }; class Derived2 : public Base { public: void doWork() override { std::cout << "Derived2 working." << std::endl; } }; int main() { std::unordered_map<std::type_index, std::unique_ptr<Base>> factory; // 使用 type_index 来索引不同的派生类 factory[std::type_index(typeid(Derived1))] = std::make_unique<Derived1>(); factory[std::type_index(typeid(Derived2))] = std::make_unique<Derived2>(); // 调用各个对象的 doWork 函数 for (auto& pair : factory) { pair.second->doWork(); } return 0; }执行结果为:
Derived2 working.
Derived1 working.