Search code examples
c++c++11typeid

Why does typeid print true?


I have a two test cases for std::is_same() and typeid().

case 1: For std::is_same()

#include <iostream>
#include <type_traits>
#include <cstdint>

int main()
{
    std::cout << std::boolalpha;
    std::cout << std::is_same<int, volatile int>::value << '\n'; // false
}

Output :

false

Its gives the correct output.

case 2: For typeid()

#include <iostream>
#include <cstdlib>
using namespace std;

#define CMP_TYPE(a, b)  cout<<(typeid(a) == typeid(b)) << endl;

int main()
{
    cout << std::boolalpha;
    CMP_TYPE(int, volatile int)
}

Output :

true

Why does typeid print true?


Solution

  • From CppReference.

    In all cases, cv-qualifiers are ignored by typeid (that is, typeid(T) == typeid(const T))

    Which means that I can get this work:

    #define TYPECMP(T, U) (typeid(T) == typeid(U))
    assert(TYPECMP(int, const int));
    assert(TYPECMP(int, volatile int));
    assert(TYPECMP(int, const volatile int));
    assert(TYPECMP(const int, volatile int));