首页 > 解决方案 > const 好的,但不是 constexpr?

问题描述

使用constexpr-specified 函数foo_constexpr,我有如下所示的代码:

const auto x = foo_constexpr(y);
static_assert(x==0);

x当声明更改为时,在哪些情况下代码可能无法编译constexpr?(毕竟,x必须已经是一个常量表达式,以便在 . 中使用static_assert。)即:

constexpr auto x = foo_constexpr(y);
static_assert(x==0);

标签: c++c++11constantsconstexpr

解决方案


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.


推荐阅读