Here is example from 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));
}
}
As you can see std::is_constant_evaluated()
. My question is why can't we use if constexpr
here to check if the function call occurs within a constant-evaluated context?