When does a constexpr function get evaluated at compile time?
constexpr
functions will be evaluated at compile time when all its arguments are constant expressions and the result is used in a constant expression as well. A constant expression could be a literal (like 42
), a non-type template argument (like N
in template<class T, size_t N> class array;
), an enum
element declaration (like Blue
in enum Color { Red, Blue, Green };
, another variable declared constexpr, and so on.
They might be evaluated when all its arguments are constant expressions and the result is not used in a constant expression, but that is up to the implementation.
The function has to be evaluated at compile-time when a constant expression is needed.
The simplest method to guarantee this is to use a constexpr
value, or std::integral_constant
:
constexpr auto result = POW(i, 2); // this should not compile since i is not a constant expression
std::cout << result << std::endl;
or:
std::cout << std::integral_constant<int, POW(i, 2)>::value << std::endl;
or
#define POW_C(base, power) (std::integral_constant<decltype(POW((base), (power)), POW((base), (power))>::value)
std::cout << POW_C(63, 2) << std::endl;
or
template<int base, int power>
struct POW_C {
static constexpr int value = POW(base, power);
};
std::cout << POW_C<2, 63>::value << std::endl;