Can't Use Function Parameter of a constexpr Function in a Constant Expression
The code snippet provided shows a constexpr function make_const and a function t1 that attempts to use make_const with a non-constant expression. This raises an error because i in t1 is not a constant expression.
A constexpr function, when given constant arguments, can be evaluated at compile time. However, if a non-constexpr parameter is passed to a constexpr function, it does not make that parameter a constant expression.
In the code below, t1 is a constexpr function, but make_const(i) inside t1 is not a constant expression because i is not a constant:
constexpr int t1(const int i) { return make_const(i); }
The updated code shows that t1 can be declared as constexpr and return the result of make_const:
constexpr int t1(const int i) { return make_const(i); }
However, the code below will still result in an error because do_something
template<int i> constexpr bool do_something(){ return i; } constexpr int t1(const int i) { return do_something<make_const(i)>(); }
To summarize, a constexpr function parameter must be a constant expression. If a non-constant parameter is passed, it does not become a constant expression within the constexpr function.
The above is the detailed content of Why Can't I Use a Function Parameter in a `constexpr` Function as a Constant Expression?. For more information, please follow other related articles on the PHP Chinese website!