bobeff bobeff - 1 month ago 13
C++ Question

What is the rationale behind decltype behavior?

As I understood in C++11

decltype(expression)
is used to deduce the exact same type of the given expression. But when the expression is put into parentheses itself, then the deduces type is lvalue reference to the expression type. For example:

int x;
decltype(x) y = x;


is equivalent to
int y = x;
but,

int x;
decltype((x)) y = x;


is equivalent to
int& y = x;
.

Respectively

decltype(auto) f1()
{
int x = 0;
return x; // decltype(x) is int, so f1 returns int
}


but

decltype(auto) f2()
{
int x = 0;
return (x); // decltype((x)) is int&, so f2 returns int&
}


What is the rationale for this behavior to be chose by the standard committee?

Afterwords:

Now I observed that at least in the case of GCC 6.2 implementation when the expression in the parentheses is more complex for example
decltype((x + x))
the deduced type is
T
, but not
T&
. This is even more confusing. I don't know whether this behavior is standard.

Answer

They wanted a way to get the type of declaration of an identifier.

They also wanted a way to get the type of an expression, including information about if it is a temporary or not.

decltype(x) gives the declared type of the identifier x. If ypu pass decltype something that is not an identifier, it determines the type, then appends & or && depending on if it is an lvalue or rvalue.

Conceptually you can think of it as the difference between the type of a variable and the type of an expression. But that is not quite how the standard describes it.

They could have used two different keywords to mean these two things. They did not.

Comments