我有一个关于decltype
的问题。对于以下代码:
#include <iostream>
#include <type_traits>
int main()
{
int a[3];
std::cout << std::is_same_v<decltype((a)), int(&)[3]> << std::endl;
std::cout << std::is_same_v<decltype(a + 0), int*> << std::endl;
}
所有输出都是 1。但正如 cppreference 所说:
If the argument is any other expression of type
T
, and if the value category ofexpression
is lvalue (or pvalue), then decltype yieldsT&
(orT
);
我不明白为什么decltype((a))
是int(&)[3]
,因为
a
是数组变量,不是左值(a)
是一个表达式,所以我认为decltype((a))
应该返回它的类型,它应该被衰减为int *
,如第二个输出所示。
所以基本上,在使用 decltype
时,我不明白 (a)
和 a + 0
之间的区别。
最佳答案
a
is an array variable, which is not a lvalue
a
既是变量名又是表达式。变量本身没有值类别,但当用作表达式时,它是左值。
(a)
是一个表达式,完全等同于表达式a
。 (a)
显然不是变量名。
I think
decltype((a))
should return its type
正如您引用的那样,对于表达式,decltype
还通过添加 &
、&&
或没什么。由于 (a)
是左值,因此添加了 &
。
should be decayed as
int*
数组到指针的衰减并不总是发生。它发生在数组的大多数使用过程中,但不是全部。
特别是,将数组传递给 decltype
时不会发生这种情况。
as the second output shows
在第二种情况下,将 +
应用于数组会强制其衰减为指针。
生成的指针是纯右值,因此报告的类型不是引用。
关于c++ - 带有 C++ 数组的 decltype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66924236/