user2449761
user2449761

Reputation: 1229

typeid / type_info strange behaviour

Why following example:

#include <iostream>
#include <typeinfo>

template<typename T>
void fun(const T& param)
{
        std::cout << "T = " << typeid(T).name() << std::endl;
        std::cout << "param = " << typeid(param).name() << std::endl;
        std::cout << (typeid(T)==typeid(param)) << std::endl;
}

int main(int, char**)
{
        fun(1);
}

gives following output:

T is i
param is i
1

I know that type_info::name() behaviour is implementation dependent. Anyway I would expect operator== to return false (because param is a const reference and not an integer).

Upvotes: 7

Views: 551

Answers (1)

Christophe
Christophe

Reputation: 73366

This is defined so in the standard:

5.2.8/5: If the type of the expression or type-id is a cv-qualified type, the result of the typeid expression refers to a std::type_info object representing the cv-unqualified type [Example:

class D { /* ... */ };
D d1;
const D d2;
typeid(d1) == typeid(d2); // yields true
typeid(D) == typeid(const D); // yields true
typeid(D) == typeid(d2); // yields true
typeid(D) == typeid(const D&); // yields true

—end example ]

Upvotes: 16

Related Questions