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.
CodePudding user response:
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 therefore decltype(x[0])
is double&
, not double
. The variable d3
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 of decltype
is just an unparanthesized name, it will result in the type with which the name is declared, so here double
.
If you used decltype((n1))
instead, the previous value category rules would apply and it would be double&
again.
CodePudding user response:
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.
So if you don't use auto, then you can actually write:
double n1 = x[0]
, or
double &n1 = x[0]
.
As said, auto
preserves the minimum information, so your code is evaluated to the first one.
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.