Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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";
} 
like image 345
Helmut Zeisel Avatar asked Sep 10 '25 03:09

Helmut Zeisel


2 Answers

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.

like image 172
songyuanyao Avatar answered Sep 12 '25 18:09

songyuanyao


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
like image 31
273K Avatar answered Sep 12 '25 16:09

273K