const好,但不是constexpr?

use*_*370 7 c++ const constexpr c++11

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

const auto x = foo_constexpr(y);
static_assert(x==0);
Run Code Online (Sandbox Code Playgroud)

在的声明x更改为的情况下,代码在什么情况下然后可能无法编译constexpr?(毕竟,x必须已经是用于中的常量表达式static_assert。)即:

constexpr auto x = foo_constexpr(y);
static_assert(x==0);
Run Code Online (Sandbox Code Playgroud)

Sto*_*ica 8

一般的,它可以编译失败时的执行foo_constexpr违反常量表达式的要求。请记住,constexpr函数并非始终是常量表达式的函数。而是一个函数,它可以为一个输入至少生成一个常数表达式!而已。

因此,如果我们要编写此完全合法的函数:

constexpr int foo_constexpr(int y) {
  return y < 10 ? 2*y : std::rand();
}
Run Code Online (Sandbox Code Playgroud)

然后我们将得到:

constexpr int y = 10;
const     auto x1 = foo_constexpr(y); // valid, execution time constant
constexpr auto x2 = foo_constexpr(y); // invalid, calls std::rand
Run Code Online (Sandbox Code Playgroud)

但是,当然,如果x在常量表达式(例如静态断言)中已经可用,则更改为constexpr不会导致失败。