typeid / type_info strange behaviour
Asked Answered
V

1

7

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

Villiers answered 11/12, 2016 at 14:31 Comment(5)
In your code you use == but in your question !=. Clarify.Westward
typeid ignores top-level qualifiers (including references).Folder
sorry, fixed itVilliers
Are you expecting output int? If so, fine print: filter through c++filt -t if using gcc or similar.Fishmonger
I should be more precise: typeid can be applied to either a type or an expression (just like sizeof). The expression param is of type const T (remember, expressions are values, never references). And typeid ignores the top-level cv-qualifiers.Folder
F
16

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 ]

Felicio answered 11/12, 2016 at 14:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.