Why use std::type_index instead of std::type_info*

转自:  http://stackoverflow.com/questions/20022546/why-use-stdtype-index-instead-of-stdtype-info


------------------------------------------------------Ask--------------------------------------------------------------------------

I need to key some data in a map by a type. Currently I have something like this:

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;

Which I can then look up from using (for example, in a template method having <typename T>:

auto pair = d_fooByTypeId.find(&typeid(T));

However today I was reading about std::type_index which seems to be intended for use in such a case as this.

I'm interested in improving my C++ knowledge. Can someone please explain whether I should modify my code to use std::type_index, and why? Is there a reason beyond being able to remove the TypeInfoComparer?

----------------------------------------------------Answer---------------------------------------------------------------------------

type_index is "a simple wrapper for type_info which can be used as an index type in associative containers (23.4) and in unordered associative containers (23.5)". If you use type_index instead of type_info*, you will free yourself from having to provide an explicit comparator in your maps. The only cost is that you need to #include <typeindex>.

Another benefit is that it will allow you to switch to (or also use) hashmaps (aka unordered_maps).

On the whole, since it simplifies your code, I'd say "go for it".






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值