std::is_constant_evaluated
We can use std::is_constant_evaluated function to determine if the constexpr function is called from constant expression context. For example,
#include <type_traits>
constexpr int max(int a, int b)
{
if (std::is_constant_evaluated())
return 10;
return a < b ? b : a;
}
int result{max(1, 2)};
std::cout << result << "\n";
constexpr int result2{max(1, 2)};
std::cout << result2 << "\n";For the first time, max is called in non-constant-expression context, so std::is_constant_evaluated returns false. We get result as 2.
Next time, max is called in constant expression context, so std::is_constant_evaluated returns true and we get 10 as result.
We can use if consteval syntax for the same purpose as shown below:
constexpr int min(int a, int b)
{
if consteval
{
return 10;
}
return a < b ? a : b;
}Note
std::is_constant_evaluatedandif constevaldo not tell if the function is evaluated at compile time or runtime, they just tell ifconstexprfunction is invoked in constant expression contexts.