auto/ decltype 错误 我很好奇为什么代码不起作用。 (E0252)
int main()
{
double x[3] = { 1,2,3 };
auto n1 = x[0];
decltype(n1) d1 = n1;
decltype(n1) d2; // ok
decltype(x[0]) d3; // error
}
我是一名初学者,第一次使用堆栈溢出。使用以下代码中的类型时出现错误,我想知道为什么。我需要聪明人的帮助。
int main()
{
double x[3] = { 1,2,3 };
auto n1 = x[0];
decltype(n1) d1 = n1;
decltype(n1) d2; // ok
decltype(x[0]) d3; // error
}
I am a beginner user who uses stack overflow for the first time. An error occurs when using the type in the following code, and I want to know why. I need the help of smart people.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当 decltype 应用于不仅是不带括号的名称的表达式时,它不仅使用表达式的类型,还使用其值类别。
如果值类别是左值,那么它将产生左值引用,如果它是x值,它将产生右值引用,如果它是纯右值,它将产生非引用。
在您的情况下,
x[0]
是左值,因此decltype(x[0])
是double&
,而不是double< /代码>。变量 d3 是一个引用,它的定义中始终必须有一个初始值设定项,但这里没有。
decltype(n1)
是不同的。如果decltype
的操作数只是一个未加括号的名称,它将产生声明该名称所用的类型,所以这里是double
。如果您使用
decltype((n1))
来代替,则将应用之前的值类别规则,并且它将再次变为double&
。When
decltype
is applied to an expression which is not only an unparenthesized name, it does not only use the type of the expression, but also its value category.If the value category is lvalue, then it will produce a lvalue reference, if it is xvalue, it will produce a rvalue reference and if it is prvalue, it will produce a non-reference.
In your case
x[0]
is a lvalue and thereforedecltype(x[0])
isdouble&
, notdouble
. The variabled3
is then a reference, which always must have an initializer in its definition, which it doesn't have here.decltype(n1)
is different. If the operand ofdecltype
is just an unparanthesized name, it will result in the type with which the name is declared, so heredouble
.If you used
decltype((n1))
instead, the previous value category rules would apply and it would bedouble&
again.上面的答案已经很清楚了。但为了让您轻松记住它,我想将
auto
和decltype
视为这样:auto
保留最少的信息,而decltype
保留最大信息。所以如果你不使用auto,那么你实际上可以这样写:
double n1 = x[0]
,或者双精度&n1 = x[0]
。如前所述,
auto
保留最少的信息,因此您的代码将被评估为第一个代码。decltype
保留最大信息,因此decltype(x[0])
相当于double &
,这就是为什么您不能编写最后一条语句,因为您必须初始化引用。The answer above is pretty clear. But for you to remember it easily, I would like to think
auto
anddecltype
as such:auto
preserves the minimum information, whiledecltype
preserves maximum information.So if you don't use auto, then you can actually write:
double n1 = x[0]
, ordouble &n1 = x[0]
.As said,
auto
preserves the minimum information, so your code is evaluated to the first one.decltype
preserves maximum information, sodecltype(x[0])
is equivalent todouble &
, which is why you cannot write your last statement as you must initialize a reference.