Why use std::type_index instead of std::type_info*
来源:互联网 发布:手机外形设计软件 编辑:程序博客网 时间:2024/09/21 09:05
转自: 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
?
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".
- Why use std::type_index instead of std::type_info*
- Why should I use XML instead of HTML?
- Why Use Git Instead of a Legacy Version Control System
- Why use MTP instead of USB Mass Storage
- Why we should use ENUM instead of String ?
- Why does MariaDB 10.2 use InnoDB instead of XtraDB?
- shared_ptr.hpp(321) : error C2039: 'type_info' : is not a member of 'std' 错误修正
- Item21 Perfer std::make_unique and std::make_shared to direct use of new
- std
- std
- std
- Why don't we use a constructor instead of factory method?
- storm杂谈之Why use netty as transport instead of zeromq
- Using a std::unordered_set of std::unique_ptr
- use supervisor instead of nohup
- Smart Pointers - What, Why, Which?- std::auto_ptr
- Why I Prefer '' to std::endl 译文
- Why Using Sockets instead of Remoting
- Android多线程相关处理及用法
- 移动云VPC对标分析
- 连接器脚本
- LeetCode 55. Jump Game 解题报告
- Android databinding详解(二)--activity解析
- Why use std::type_index instead of std::type_info*
- C#开发WebService笔记
- OpenSSL---概述
- 【转】阻塞与非阻塞socket的优缺点
- 线程安全的集合
- 根据日期获取星期几的两种方法
- 简洁精美源于分析透彻,构思明确、求精,逻辑练达。(14)
- 给你一个网站,你将如何测试?
- Spring mvc解决url传递中文参数乱码问题