std::is_constant_evaluated
From cppreference.com
| Defined in header <type_traits>
|
||
constexpr bool is_constant_evaluated() noexcept;
|
(since C++20) | |
Detects whether the function call occurs within a constant-evaluated context. Returns true if the evaluation of the call occurs within the evaluation of an expression or conversion that is manifestly constant-evaluated; otherwise returns false.
To determine whether initializers of following variables are manifestly constant-evaluated, compilers may first perform a trial constant evaluation:
- variables with reference type or const-qualified integral or enumeration type;
- static and thread local variables.
It is not recommended to depend on the result in this case.
int y = 0;
const int a = std::is_constant_evaluated() ? y : 1;
// Trial constant evaluation fails. The constant evaluation is discarded.
// Variable a is dynamically initialized with 1
const int b = std::is_constant_evaluated() ? 2 : y;
// Constant evaluation with std::is_constant_evaluated() == true succeeds.
// Variable b is statically initialized with 2
Parameters
(none)
Return value
true if the evaluation of the call occurs within the evaluation of an expression or conversion that is manifestly constant-evaluated; otherwise false.
Possible implementation
// This implementation requires C++23 if consteval.
constexpr bool is_constant_evaluated() noexcept
{
if consteval
{
return true;
}
else
{
return false;
}
}
|
Notes
When directly used as the condition of static_assert declaration or