Why is this an issue?
std::is_constant_evaluated
is used to determine whether or not a context is constant-evaluated. This can be useful when, for example,
two different implementations are provided for an algorithm: one, usually slow, for compile-time and the other one, faster, for runtime.
However, some contexts are either always constant-evaluated or never constant-evaluated. In these cases, a call to
std::is_constant_evaluated
is unnecessary as it will always return the same result.
std::is_constant_evaluated
will always return true
when called in:
- the condition of
if constexpr
- the condition of
static_assert
-
consteval
functions
And it will always return false
in:
- non-
constexpr
/consteval
functions
This rule raises an issue when std::is_constant_evaluated()
is called in an if constexpr
or a static_assert
condition, where it is always true
.
Noncompliant code example
constexpr double power(double b, int x) {
if constexpr (std::is_constant_evaluated()) { // Noncompliant: will always be true
// compile-time implementation
} else {
// runtime implementation
}
}
Compliant solution
constexpr double power(double b, int x) {
if (std::is_constant_evaluated()) {
// compile-time implementation
} else {
// runtime implementation
}
}