As a general rule, decltype
preserves constness:
const int ci = 0;
decltype(ci) x; // x is const int
x = 5; // error--x is const
class Gadget{}:
const Gadget makeCG(); // factory
decltype(makeCG()) y1, y2; // y1 and y2 are const Gadgets
y1 = y2; // error--y1 is const
But for const
return types that return fundamental types, decltype
seems to throw const
away:
const int makeCI(); // factory
decltype(makeCI()) z; // z is NOT const
z = 5; // okay
Why does decltype
discard constness in this case? I mean the question in two ways:
Thanks.
The behavior you observe is correct: decltype(makeCI())
is int
, not int const
.
The makeCI()
function call expression is a prvalue expression. Per C++11 §3.10[basic.lval]/4:
Class prvalues can have cv-qualified types; non-class prvalues always have cv-unqualified types.
The term "cv-qualification" refers to const- and volatile-qualification. int
is not a class type, so the type of the rvalue expression makeCI()
is int
and it is not const-qualified.
(In recent drafts of the C++ language standard, e.g. N3690, this text has been removed and replaced by new text at §5[expr]/6, which states, "If a prvalue initially has the type "cv T," where T is a cv-unqualified non-class, non-array type, the type of the expression is adjusted to T prior to any further analysis." See CWG defect 1261 for details.)
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