Consider the following code:
int a = 1;
const int& b = a;
std::cout << std::is_same<const decltype(b)&, const int&>();
It compiles on clang 3.5 while GCC 4.9 gives the following error:
error: 'const' qualifiers cannot be applied to 'const int&'
Which one is correct according to the standard? My guess is that GCC is standard-conformant, just as you can't do int& const b = a;
.
The following expressions do not evaluate their operands: sizeof() , typeid() , noexcept() , decltype() , and declval() .
decltype is a compile time evaluation (like sizeof ), and so can only use the static type.
'auto' lets you declare a variable with a particular type whereas decltype lets you extract the type from the variable so decltype is sort of an operator that evaluates the type of passed expression.
The decltype type specifier yields the type of a specified expression. The decltype type specifier, together with the auto keyword, is useful primarily to developers who write template libraries. Use auto and decltype to declare a function template whose return type depends on the types of its template arguments.
I believe the code is valid and the two types are the same.
[dcl.ref]/1 says:
Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name (7.1.3, 14.1) or decltype-specifier (7.1.6.2), in which case the cv-qualifiers are ignored.
Since you are introducing the first const
through a decltype-specifier, it is ignored, and your first type is equivalent to decltype(b)&
.
Now [dcl.ref]/6 says:
If a typedef-name (7.1.3, 14.1) or a decltype-specifier (7.1.6.2) denotes a type
TR
that is a reference to a typeT
, an attempt to create the type "lvalue reference to cvTR
" creates the type "lvalue reference toT
" [...]
Your decltype-specifier denotes the type "reference to const int
", and you are attempting to create an lvalue reference, so you end up with an lvalue reference to const int
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With