简体   繁体   中英

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM