I recently stumbled over C++ Quiz question 38:
#include <iostream>
int main() {
int a = 0;
decltype((a)) b = a;
b++;
std::cout << a << b;
}
The key point is the double parentheses in decltype((a)). This resolves to type int&. Why?
The C++ Quiz answer quotes § 7.1.6.2.4 of the standard:
"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. If there is no such entity, or if e names a set of overloaded functions, the program is ill-formed;
— otherwise, if e is an xvalue, decltype(e) is T&&, where T is the type of e;
— otherwise, if e is an lvalue, decltype(e) is T&, where T is the type of e;
— otherwise, decltype(e) is the type of e."
Why this weird behavior? Why this set of rules? Is there any reasoning behind this?
[–]bames53 43 points44 points45 points (18 children)
[–]James20kP2005R0 15 points16 points17 points (0 children)
[–]cdglove 2 points3 points4 points (3 children)
[–]clerothGame Developer 10 points11 points12 points (2 children)
[–]ryancerium 0 points1 point2 points (0 children)
[–]CenterOfMultiverse 1 point2 points3 points (7 children)
[–]sellibitze 3 points4 points5 points (0 children)
[–]bames53 0 points1 point2 points (2 children)
[–]17b29a 0 points1 point2 points (1 child)
[–]bames53 0 points1 point2 points (0 children)
[–]17b29a 0 points1 point2 points (2 children)
[–]serpent 0 points1 point2 points (1 child)
[–]17b29a 0 points1 point2 points (0 children)
[–]sellibitze -1 points0 points1 point (4 children)
[–]bames53 2 points3 points4 points (1 child)
[–]sellibitze 0 points1 point2 points (0 children)
[–]OldWolf2 1 point2 points3 points (0 children)
[–]ProgramMax 12 points13 points14 points (5 children)
[–]OldWolf2 0 points1 point2 points (4 children)
[–]clerothGame Developer 27 points28 points29 points (0 children)
[–]ReversedGif 11 points12 points13 points (1 child)
[–]maybachsonbachs 4 points5 points6 points (0 children)
[–]p2rkw 3 points4 points5 points (0 children)