Search code examples
c++type-traitstypeidtypeinfo

Why are these types not the same?


Why do T1 and T2 have the same typeid but are not the same type? (The output is 1 0)

#include <iostream>
#include <typeinfo>
#include <type_traits>

int main()
{
  using T1 = decltype("A");
  using T2 = const char[2];
  std::cout << (typeid(T1) == typeid(T2)) << "\n";
  std::cout << std::is_same_v<T1,T2> << "\n";
} 

Solution

  • String literal like "A" is lvalue expression, as the effect decltype leads to lvalue-reference, so T1 would be const char (&)[2].

    if the value category of expression is lvalue, then decltype yields T&;

    T2 is const char[2], and typeid on T1 will give the result referring to the referenced type, i.e., const char[2], that's why typeid(T1) == typeid(T2) is true, but std::is_same_v<T1,T2> is false.

    If type is a reference type, the result refers to a std::type_info object representing the cv-unqualified version (since C++11) of the referenced type.