According to this answer, ref
should be an int
.
But for some reason it evaluated to int&
, both in gcc and MSVC2015, while decltype(b)
is correctly evaluated to just int
. Why so?
int a = 1, b = 2;
decltype(a, b) ref; // ref is int&
decltype(b) var; // var is int
Otherwise, E ’s exprtype is an lvalue reference. An unintuitive consequence of this rule is that the reference qualification on E ’s expression decltype is generally independent of that on its variable decltype. For example, v and vref have the same exprtype, as do s.lref and s.rref.
To make it reference type, we use auto &. 2) decltype Keyword: It inspects the declared type of an entity or the type of an expression. ‘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.
If there is no such entity, or if the argument names a set of overloaded functions, the program is ill-formed. If the argument is an unparenthesized id-expression naming a structured binding, then decltype yields the referenced type (described in the specification of the structured binding declaration).
decltype Keyword It inspects the declared type of an entity or the type of an expression. Auto lets you declare a variable with 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. Explanation of above keyword and their uses is given below:
a, b
is an expression. According to decltype
rules for expressions, if result of the expression is an lvalue, type is going to be deduced as T&
7.1.6.2/4 Simple type specifiers [dcl.type.simple]
For an expression e, 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.
The confusing part about difference between "type of the entity named by e
" and "type of e
" is easy to understand with example:
If some entity e
is declared as int& e = x;
, then later, in expression e
, type of e
is int
, and type of the entity named by e
is int&
. In short, type of e
drops reference qualifiers.
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