< cpp‎ | types
Revision as of 09:21, 27 April 2013 by Eendy (Talk | contribs)

Type support
Basic types
Fundamental types
Fixed width integer types (C++11)
Numeric limits
C numeric limits interface
Runtime type information
Type traits
Type categories
Type properties
Type trait constants
Supported operations
Relationships and property queries
Type modifications
Type transformations

Template:ddcl list begin <tr class="t-dsc-header">

Defined in header <typeindex>

<td></td> <td></td> </tr> <tr class="t-dcl ">

<td >
class type_index;

<td class="t-dcl-nopad"> </td> <td > (since C++11) </td> </tr> Template:ddcl list end

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

constructs the object
(public member function) [edit]
compares the underlying std::type_info objects
(public member function) [edit]
returns hashed code
(public member function) [edit]
returns implementation defined name of the type,
associated with underlying type_info object
(public member function) [edit]

Helper classes

hash support for std::type_index
(class template specialization) [edit]


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

#include <iostream>
#include <typeinfo>
#include <typeindex>
#include <unordered_map>
#include <string>
#include <memory>
struct A {
    virtual ~A() {}
struct B : A {};
struct C : A {};
int main()
    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";
    int i;
    double d;
    A a;
    // note that we're storing pointer to type A
    std::unique_ptr<A> b(new B);
    std::unique_ptr<A> c(new C);
    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';


i is int
d is double
a is A
b is B
c is C

See also

contains some type's information, generated by the implementation.
This is the class returned by the typeid operator.
(class) [edit]