Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

rtti

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?

like image 803
Drew Noakes Avatar asked Nov 16 '13 19:11

Drew Noakes


People also ask

What is std :: type_index for?

std::type_index The type_index class is a wrapper class around a std::type_info object, that can be used as index in associative and unordered associative containers. The relationship with type_info object is maintained through a pointer, therefore type_index is CopyConstructible and CopyAssignable.

What is std :: type_info?

std::type_info The class type_info holds implementation-specific information about a type, including the name of the type and means to compare two types for equality or collating order. This is the class returned by the typeid operator.

How do you use Typeid?

To use the typeid operator in a program, one needs to include the library header <typeinfo>. It returns the lvalue of type const type_info to represent the type of value. Expression of typeid is an lvalue expression (lvalue has the address which is accessible by the program.


2 Answers

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".

like image 91
rici Avatar answered Sep 28 '22 02:09

rici


I don't think using a pointer to the result returned from typeid(x) is guaranteed to always yield the same result. In particular it seems problematic to guarantee the same object to be returned when shared libraries are used. The intended use of std::type_info for sorting is to use before() member. The class std::type_index wraps this into a simoler interface.

like image 27
Dietmar Kühl Avatar answered Sep 28 '22 04:09

Dietmar Kühl