std::is_constant_evaluated

From cppreference.com
< cpp‎ | types
 
 
 
Type support
Basic types
Fundamental types
Fixed width integer types (C++11)
Numeric limits
C numeric limits interface
Runtime type information
Type traits
Type categories
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
Type properties
(C++11)
(C++11)
(C++14)
(C++11)
(C++11)(until C++20)
(C++11)(deprecated in C++20)
(C++11)
Type trait constants
Metafunctions
(C++17)
Endian
(C++20)
Constant evaluation context
is_constant_evaluated
(C++20)
Supported operations
Relationships and property queries
(C++11)
(C++11)
Type modifications
(C++11)(C++11)(C++11)
Type transformations
(C++11)
(C++11)
(C++17)
(C++11)(until C++20)(C++17)
 
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.

The following expressions (including conversions to the destination type) are manifestly constant-evaluated:

  • Where a constant expression is grammatically required, including:
  • initializers of static and thread local variables, when all subexpressions of the initializers (including constructor calls and implicit conversions) are constant expressions (that is, when the initializers are constant initializers)

To test the last two conditions, compilers may first perform a trial constant evaluation of the initializers. It is not recommended to depend on the result in this case.

int y;
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_evaluation() == 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

Notes

When directly used as the condition of static_assert declaration or constexpr if statement, std::is_constant_evaluated() always returns true.

Example