Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issues concerning const decltype(x)&

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;.

like image 494
Lingxi Avatar asked Apr 09 '15 14:04

Lingxi


People also ask

Does decltype evaluate expression?

The following expressions do not evaluate their operands: sizeof() , typeid() , noexcept() , decltype() , and declval() .

Is decltype runtime or compile time?

decltype is a compile time evaluation (like sizeof ), and so can only use the static type.

What is the difference between auto and decltype Auto?

'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.

What is the use of decltype in C++?

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.


1 Answers

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 type T, an attempt to create the type "lvalue reference to cv TR" creates the type "lvalue reference to T" [...]

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.

like image 100
Kerrek SB Avatar answered Sep 27 '22 16:09

Kerrek SB