Reputation: 694
Here, at http://eel.is/c++draft/expr.const#2.7 it can be read
3 - A variable is usable in constant expressions after its initializing declaration is encountered if it is a constexpr variable, or it is of reference type or of const-qualified integral or enumeration type, and its initializer is a constant initializer.
Well, the case is that I cannot figure myself an example for the case where the variable is of reference type.
In
int main()
{
static const double& ds = 0.5;
constexpr double cds = ds;
}
Visual Studio 16.1.2 complains:
expression must have a constant value.
the value of variable (declared at line 11) cannot be used as a constant
But, why?
Upvotes: 1
Views: 1150
Reputation: 141618
Your code is not legal in C++17 because it contains a constexpr
variable whose initialization requests lvalue-to-rvalue conversion and it is not one of the listed exceptions: (C+17 [expr.const]/2.7)
an lvalue-to-rvalue conversion (7.1) unless it is applied to
- a non-volatile glvalue of integral or enumeration type that refers to a complete non-volatile const object with a preceding initialization, initialized with a constant expression, or
- a non-volatile glvalue that refers to a subobject of a string literal, or
- a non-volatile glvalue that refers to a non-volatile object defined with constexpr , or that refers to a non-mutable subobject of such an object, or
- a non-volatile glvalue of literal type that refers to a non-volatile object whose lifetime began within the evaluation of
e
;
You should find the code compiles if you change to an integer type instead of double
.
The text you quote is from a draft and as such, may or may not eventually form part of some standard.
Upvotes: 2