bobeff bobeff - 1 year ago 63
C++ Question

What is the rationale behind decltype behavior?

As I understood in C++11

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;

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

is equivalent to
int& y = x;


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


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?


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
, but not
. This is even more confusing. I don't know whether this behavior is standard.

Answer Source

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.