为什么使用std :: type_index而不是std :: type_info*

Dre*_*kes 26 c++ rtti c++11

我需要按类型键入地图中的一些数据.目前我有这样的事情:

struct TypeInfoComparer
{
  bool operator()(std::type_info const* a, std::type_info const* b) const
  {
    return a->before(*b);
  };
};

std::map<std::type_info const*, Foo, TypeInfoComparer> d_fooByTypeId;
Run Code Online (Sandbox Code Playgroud)

然后我可以从使用中查找(例如,在模板方法中<typename T>:

auto pair = d_fooByTypeId.find(&typeid(T));
Run Code Online (Sandbox Code Playgroud)

然而今天我正在阅读std::type_index哪些似乎打算用于这种情况.

我有兴趣提高我的C++知识.有人可以解释我是否应该修改我的代码使用std::type_index,为什么?有没有理由除了能够删除TypeInfoComparer

ric*_*ici 22

type_index是"type_info的简单包装器,可以在关联容器(23.4)和无序关联容器(23.5)中用作索引类型".如果您使用type_index而不是type_info*,您将不必在地图中提供明确的比较器.唯一的代价是你需要的#include <typeindex>.

另一个好处是它允许您切换到(或使用)hashmaps(也称为unordered_maps).

总的来说,因为它简化了你的代码,我会说"去吧".

  • 并且没有理由使用`map`,因为`before`顺序是任意的. (2认同)

Die*_*ühl 6

我认为使用指针不能typeid(x)保证总是返回相同的结果。特别是在使用共享库时,保证返回相同的对象似乎是有问题的。std::type_info排序的预期用途是使用before()成员。该类std::type_index将其包装为simoler接口。

  • @Nawaz“无法保证相同类型的typeid表达式的所有求值都引用相同的std :: type_info实例。” https://en.cppreference.com/w/cpp/ “注释”下的语言/类型 (3认同)