Why are these types not the same?

141 Views Asked by At

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";
} 
2

There are 2 best solutions below

0
leslie.yao On BEST ANSWER

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.

5
273K On

T1 has type const char(&)[2]. A reference is an alias of const char[2] and has the same typeid.

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

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

Output

1
1