std::type_index - cppreference.com

From cppreference.com

classtype_index;(since C++11)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

.

Member functions

(constructor)

constructs the object
(public member function)

[edit]

(destructor)

(implicitly declared)

destroys the type_index object
(public member function)operator=

(implicitly declared)

assigns a type_index object
(public member function)

operator==operator!=operator<operator<=operator>operator>=operator<=>

(removed in C++20)(C++20)

compares the underlying

std::type_index

objects
(public member function)

[edit]

hash_code

returns hashed code
(public member function)

[edit]

name

returns implementation defined name of the type,
associated with underlying

type_info

object
(public member function)

[edit]

Helper classes

Example

The following program is an example of an efficient type-value mapping.

Run this code

#include<iostream>#include<memory>#include<string>#include<typeindex>#include<typeinfo>#include<unordered_map>structA{virtual~A(){}};structB:A{};structC:A{};intmain(){std::unordered_map<std::type_index,std::string>type_names;type_names[std::type_index(typeid(int))]="int";type_names[std::type_index(typeid(double))]="double";type_names[std::type_index(typeid(A))]="A";type_names[std::type_index(typeid(B))]="B";type_names[std::type_index(typeid(C))]="C";inti;doubled;Aa;// note that we're storing pointer to type Astd::unique_ptr<A>b(newB);std::unique_ptr<A>c(newC);std::cout<<"i is "<<type_names[std::type_index(typeid(i))]<<'\n';std::cout<<"d is "<<type_names[std::type_index(typeid(d))]<<'\n';std::cout<<"a is "<<type_names[std::type_index(typeid(a))]<<'\n';std::cout<<"*b is "<<type_names[std::type_index(typeid(*b))]<<'\n';std::cout<<"*c is "<<type_names[std::type_index(typeid(*c))]<<'\n';}Output:

i is int d is double a is A *b is B *c is C See also

contains some type’s information, the class returned by the typeid operator
(class)

[edit]

typeid

queries information of a type, returning a

std::type_info

object representing the type
(built-in operator)

[edit]