Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typeid / type_info strange behaviour

Tags:

c++

typeid

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

like image 989
user2449761 Avatar asked Dec 11 '16 14:12

user2449761


1 Answers

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 ]

like image 73
Christophe Avatar answered Oct 20 '22 18:10

Christophe