With a constexpr
-specified function foo_constexpr
I have code such as shown below:
const auto x = foo_constexpr(y);
static_assert(x==0);
Under which circumstances could the code then fail to compile, when the declaration of x
is changed to constexpr
? (After all, x
must already be a constant expression for use in the static_assert
.) That is:
constexpr auto x = foo_constexpr(y);
static_assert(x==0);
A constexpr variable must be initialized at compile time. All constexpr variables are const . A variable can be declared with constexpr , when it has a literal type and is initialized. If the initialization is performed by a constructor, the constructor must be declared as constexpr .
The short answer is that not only is static useful, it is pretty well always going to be desired. First, note that static and constexpr are completely independent of each other. static defines the object's lifetime during execution; constexpr specifies that the object should be available during compilation.
A constexpr constructor is implicitly inline.
In general, it can fail to compile when the execution of foo_constexpr
violates a requirement of constant expressions. Remember, a constexpr
function is not a function that is always a constant expression. But rather it is a function that can produce a constant expression for at lease one input! That's it.
So if we were to write this perfectly legal function:
constexpr int foo_constexpr(int y) {
return y < 10 ? 2*y : std::rand();
}
Then we'll get:
constexpr int y = 10;
const auto x1 = foo_constexpr(y); // valid, execution time constant
constexpr auto x2 = foo_constexpr(y); // invalid, calls std::rand
But of course, if x
is already usable in a constant expression (such as a static assertion), changing to constexpr
cannot cause a failure to occur.
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