简体   繁体   中英

c++11 decltype returns reference type

I am a little bit confused about why decltype with the comma operator returns reference type in some cases.

for example, in this code:

int i = 101;
decltype(1, i) var = i;
var = 20;
printf("%d\n", i); // will print 20

here, var is int& instead of int, but if I replace the second line with:

decltype(i) var = i;

it will return int!

can anyone please explain that?

decltype is special-cased for an unparenthesized id-expression to give the type of the entity, without reference qualification [dcl.type.simple] :

4 - The type denoted by decltype(e) is defined as follows:
— if e is an unparenthesized id-expression or an unparenthesized class member access (5.2.5), decltype(e) is the type of the entity named by e . [...]
— otherwise, if e is an lvalue, decltype(e) is T& , where T is the type of e ; [...]

By providing a comma expression you are disabling this special case, as with parentheses:

decltype(i)    // int
decltype((i))  // int&
decltype(1, i) // int&

(i) and 1, i are lvalue expressions, so their decltype is a reference type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM