Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is `type_info::before` useful for?

Tags:

c++

rtti

typeinfo

According to cplusplus.com, the std::type_info::before() function...

Returns true if the type precedes the type of rhs in the collation order.
The collation order is just an internal order kept by a particular implementation and is not necessarily related to inheritance relations or declaring order.

So what is it useful for?

like image 909
Paul Manta Avatar asked Dec 30 '11 18:12

Paul Manta


People also ask

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.

What is typeof in C++?

The typeof operator returns the type of its argument, which can be an expression or a type. The language feature provides a way to derive the type from an expression. Given an expression e , __typeof__(e) can be used anywhere a type name is needed, for example in a declaration or in a cast.


2 Answers

Consider you want to put your type_info objects as keys into a map<type_info*, value>. The type_info doesn't have an operator < defined, so you must provide your own comparator. The only thing that is guaranteed to work from the type_info interface is the before() function, since neither the addresses of type_info nor the name() must be unique:

struct compare {
    bool operator ()(const type_info* a, const type_info* b) const {
        return a->before(*b);
    }
};

std::map<const type_info*, std::string, compare> m;

void f() {
    m[&typeid(int)] = "Hello world";
}
like image 147
Yakov Galka Avatar answered Sep 22 '22 03:09

Yakov Galka


This is useful to define an order on typeinfo objects, e.g. to put them into a std::map. The obvious follow-up question is: why isn't it spelled operator<()? I don't know the answer to this question.

like image 38
Dietmar Kühl Avatar answered Sep 22 '22 03:09

Dietmar Kühl