为什么这些类型不一样?

Hel*_*sel 4 c++ typeid typeinfo type-traits

为什么T1和T2具有相同的typeid但类型不同?(输出是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";
} 
Run Code Online (Sandbox Code Playgroud)

S.M*_*.M. 5

T1有类型const char(&)[2]. 引用是 的别名const char[2]并且具有相同的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";
}
Run Code Online (Sandbox Code Playgroud)

输出

1
1
Run Code Online (Sandbox Code Playgroud)


son*_*yao 5

字符串文字就像"A"左值表达式,因为效果decltype导致左值引用,所以T1会是const char (&)[2]

如果表达式的值类别是左值,则 decltype 产生T&

T2isconst char[2]typeidonT1将给出引用类型的结果,即 ,const char[2]这就是为什么typeid(T1) == typeid(T2)is true,但是std::is_same_v<T1,T2>is false

如果 type 是引用类型,则结果引用表示the cv-unqualified version (since C++11)引用类型的 std::type_info 对象。