Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 848
user2912782 Avatar asked Aug 07 '14 15:08

user2912782


1 Answers

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.

like image 99
ecatmur Avatar answered Oct 04 '22 08:10

ecatmur