Since C++20, a call to std::is_constant_evaluated() can be used to determine whether the call occurs within a constant-evaluated
context.
Typically, this function is called in the condition of an if statement to optimize code: It allows different actions to be performed
depending on whether an expression is evaluated at compile-time or runtime. However, writing if (std::is_constant_evaluated()) comes with
a few caveats.
- It can be error-prone: One may be tempted to write
if constexpr instead of if but doing this always results in the
condition being true. S6169 explains this and other similar problems in greater depth.
- Because it looks like any regular
if statement with a function call, it does not stand out as something semantically different and
important.
- Immediate functions (see again S6169) cannot be invoked from such
if statements, which is counterintuitive and overly
restrictive.
For these reasons, C++23 introduced the if consteval control-flow statement. There is also a negated form: if not
consteval (or if ! consteval). These versions should be preferred since they are not error-prone, stand out with their different
and concise syntax, and do not require including <type_traits>.
This rule raises an issue when if (std::is_constant_evaluated()) or if (!std::is_constant_evaluated()) are used.