[英]auto/ decltype Error I'm curious why the code doesn't work. (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
}
I am a beginner user who uses stack overflow for the first time.我是初学者,第一次使用 stack overflow。 An error occurs when using the type in the following code, and I want to know why.
下面代码中使用type时出现错误,想知道为什么。 I need the help of smart people.
我需要聪明人的帮助。
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.当
decltype
应用于不仅是未加括号的名称的表达式时,它不仅使用表达式的类型,还使用它的值类别。
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.如果值类别是左值,那么它会产生一个左值引用,如果它是 xvalue,它会产生一个右值引用,如果它是 prvalue,它会产生一个非引用。
In your case x[0]
is a lvalue and therefore decltype(x[0])
is double&
, not double
.在您的情况下,
x[0]
是左值,因此decltype(x[0])
是double&
,而不是double
。 The variable d3
is then a reference, which always must have an initializer in its definition, which it doesn't have here.变量
d3
是一个引用,它的定义中总是必须有一个初始值设定项,而这里没有。
decltype(n1)
is different. decltype(n1)
是不同的。 If the operand of decltype
is just an unparanthesized name, it will result in the type with which the name is declared, so here double
.如果
decltype
的操作数只是一个未加括号的名称,它将导致声明该名称的类型,所以这里是double
。
If you used decltype((n1))
instead, the previous value category rules would apply and it would be double&
again.如果您改用
decltype((n1))
,则将应用先前的值类别规则,并且它将再次为double&
。
The answer above is pretty clear.上面的答案已经很清楚了。 But for you to remember it easily, I would like to think
auto
and decltype
as such: auto
preserves the minimum information, while decltype
preserves maximum information.但是为了便于记忆,我想将
auto
和decltype
视为这样: auto
保留最少的信息,而decltype
保留最多的信息。
So if you don't use auto, then you can actually write: double n1 = x[0]
, or double &n1 = x[0]
.因此,如果您不使用 auto,那么您实际上可以编写:
double n1 = x[0]
或double &n1 = x[0]
。 As said, auto
preserves the minimum information, so your code is evaluated to the first one.如前所述,
auto
保留最少的信息,因此您的代码将评估为第一个。
decltype
preserves maximum information, so decltype(x[0])
is equivalent to double &
, which is why you cannot write your last statement as you must initialize a reference. decltype
保留最大信息,因此decltype(x[0])
等同于double &
,这就是为什么您不能编写最后一条语句,因为您必须初始化一个引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.