Optimizing code in constant-evaluated contexts
In the previous two recipes, we learned about constexpr functions, which allow functions to be evaluated at compile time if all their inputs are available at compile time, and immediate functions (in C++20), which are guaranteed to always be evaluated at compile time (or otherwise, produce an error). An important aspect of constexpr
functions is constant-evaluated contexts; these are code paths where all expressions and functions are evaluated at compile time. A constant-evaluated context is useful for optimizing code more effectively. On the other hand, the invocation of immediate functions from constexpr
functions is only possible in C++23. In this recipe, we will learn about utilizing constant-evaluated contexts.
How to do it…
To determine whether a function context is constant-evaluated in order to provide compile-time implementations use the following:
- In C++20, the
std::is_constant_evaluated()
library function...