Home > Article > Backend Development > Why Can't I Use Function Parameters in Constant Expressions?
Constant expressions are expressions that can be evaluated at compile time. Constexpr functions are functions that can be evaluated at compile time if called with constexpr parameters.
In the code, the make_const function is a constexpr function. However, the parameter i in t1 is not a constexpr parameter, as it is not specified as const.
void t1(const int i) { constexpr int ii = make_const(i); // error: i is not a constant expression }
To fix this, one can either make i a constant parameter by changing its type to const int, or by defining t1 as a constexpr function itself:
void t1(const int i) // const int i to make i a constant parameter { constexpr int ii = make_const(i); }
constexpr int t1(const int i) // constexpr t1 to make t1 a constexpr function { return make_const(i); }
Another problem arises when using a constexpr function within a template function that is intended to return a constexpr value.
template<int i> constexpr bool do_something(){ return i; } constexpr int t1(const int i) { return do_something<make_const(i)>(); // error: i is not a constant expression }
In this case, the compiler cannot guarantee that the parameter i is a constant expression, as it depends on the value of the template parameter passed to do_something. To ensure that t1 can be evaluated at compile time, the template parameter i must be a constant expression.
An alternative approach is to use std::variant and std::integral_constant to create a compile-time constant that can be used in conjunction with runtime values.
template<auto I> using constant_t=std::integral_constant<decltype(I),I>; template<auto I> constexpr constant_t<I> constant_v={}; template<auto...Is> using var_enum_t=std::variant<constant_t<Is>...>;
This allows one to create a compile-time constant variant that can be selected at runtime using std::visit.
auto idx=var_index<5>(3/* 3 can be runtime */); std::visit([](auto three){ // three is a compile time value here }, idx);
The above is the detailed content of Why Can't I Use Function Parameters in Constant Expressions?. For more information, please follow other related articles on the PHP Chinese website!