Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const ok, but not constexpr?

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);
like image 240
user2023370 Avatar asked Aug 27 '19 07:08

user2023370


People also ask

Is constexpr always const?

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 .

Should constexpr always be static?

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.

Is constexpr inline by default?

A constexpr constructor is implicitly inline.


1 Answers

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.

like image 151
StoryTeller - Unslander Monica Avatar answered Oct 13 '22 19:10

StoryTeller - Unslander Monica