【发布时间】:2019-12-23 15:18:15
【问题描述】:
这是来自 cppreference 的示例:
constexpr double power(double b, int x)
{
if (std::is_constant_evaluated() && !(b == 0.0 && x < 0)) {
// A constant-evaluation context: Use a constexpr-friendly algorithm.
if (x == 0)
return 1.0;
double r = 1.0, p = x > 0 ? b : 1.0 / b;
auto u = unsigned(x > 0 ? x : -x);
while (u != 0) {
if (u & 1) r *= p;
u /= 2;
p *= p;
}
return r;
} else {
// Let the code generator figure it out.
return std::pow(b, double(x));
}
}
如您所见std::is_constant_evaluated()。我的问题是为什么我们不能在这里使用if constexpr 来检查函数调用是否发生在常量评估的上下文中?
【问题讨论】:
-
你问为什么这里不能用
if constexpr代替if? -
是的。这正是我想要理解的
-
@rudolfninja:你认为这种情况在做什么?在您看来,等效的
if constexpr条件会是什么样子?