3
votes

I am studying C++ Primer fifth edtion,and the example code really confused me.It is similar as the code below:

int i,&k=i;
decltype((i)) t;    //error: t must be initialized
decltype(k+0) s = 45;  //OK,s is int type

Why the two are expressions and the first one is reference type but the second one is int type?

1
Mostly because the standard says so. Are you looking for standards quotes or motivation? - TartanLlama
I guess here is the why (and a similar example too). - skypjack

1 Answers

2
votes
decltype((i));

Will yield a reference type since i is an lvalue. This is useful to determine the value category of any expression. Reproduced form cppreference, for parenthesized expression (emphasis mine):

a. if the value category of expression is xvalue, then decltype yields T&&;

b. if the value category of expression is lvalue, then decltype yields T&;

c. if the value category of expression is prvalue, then decltype yields T.


decltype(k+0)

Will yield the type of the result the k+0 expression will evaluate to. Just as auto val = k + 0; would deduce val.