Reputation: 141633
Is it permitted to declare a non-const reference as constexpr
? Example code:
int x = 1;
constexpr int& r = x;
This is accepted by gcc and clang (I tried several current and past versions of both, back to C++11, and all accepted it). However I think it should not be accepted because C++14 [dcl.constexpr/9] says:
if a constexpr specifier is used in a reference declaration, every full- expression that appears in its initializer shall be a constant expression
and x
is not a constant expression.
The language in the latest C++17 draft of [dcl.constexpr] changed and doesn't even mention constexpr
references explicitly any more, I can't make head nor tail of what it is trying to say about them.
Upvotes: 5
Views: 393
Reputation: 137414
Assuming that x
has static storage duration, the lvalue expression x
is a perfectly valid constant expression.
If you use x
in a context that requires a prvalue, which causes the lvalue-to-rvalue conversion to be applied to it, then the resulting prvalue expression - call it TO_RVALUE(x)
- would not be a constant expression, for obvious reasons. But in the case of reference binding, there is no such conversion.
Upvotes: 4