constexpr 函数包含一个 const - 它会在编译时被评估吗?

constexpr function contains a const - will it ever be evaluated at compile time?

请有人澄清一下(我正在使用 Visual Studio 15.9.2):

在下面的代码中,假设 Pi_cnst 在 运行 时间计算(因为以这种方式定义 Pi 需要 运行 时间计算),RAD2DEG_cnst 永远不会在编译时评估还是使用 "constexpr" 总是恢复到 "const" ?

编辑 - 添加:如果它总是恢复为 const 那么我应该期待一个警告,还是在其他方面不好,即能够如此轻松地声明一个 constexpr 来接受 body 似乎很奇怪但总是这样,它实际上从来不是一个 constexpr。我错过了什么?

constexpr double Pi_error = std::acos(-1.0); //error function call must have a constant value in a constant expression (does not compile)
const double Pi_cnst = std::acos(-1.0); //ok evaluated at run time

constexpr double Pi_expr = 3.1415926; //ok valid constexpr

constexpr double RAD2DEG_cnst(double rad) { return rad * 180.0 / Pi_cnst; } //no error or warning BUT is this ever evaluated at compile time?
constexpr double RAD2DEG_expr(double rad) { return rad * 180.0 / Pi_expr; } //ok can be evaluated at compile time

const double result1 = RAD2DEG_cnst(0.1); //evaluated at run time?
const double result2 = RAD2DEG_expr(0.2); //evaluated at compile time?

double myVariable = 0.3;
const double result3 = RAD2DEG_expr(myVariable); //ok - but can only be evaluated at run time

const double myOtherVariable = 0.4;
const double result4 = RAD2DEG_expr(myOtherVariable); //ok - evaluated at compile time because parameter is CONST?

我也找到了 and .

您的代码格式错误,无需诊断。在

constexpr double RAD2DEG_cnst(double rad) { return rad * 180.0 / Pi_cnst; }

没有使函数成为 core constant expression which is specified by [dcl.constexpr]/5

的输入

For a constexpr function or constexpr constructor that is neither defaulted nor a template, if no argument values exist such that an invocation of the function or constructor could be an evaluated subexpression of a core constant expression, or, for a constructor, a constant initializer for some object ([basic.start.static]), the program is ill-formed, no diagnostic required.