Home >Backend Development >C++ >Can Consteval Functions Allow Template Parameters Reliant on Function Arguments?
Can Consteval Functions Enable Template Parameters Reliant on Function Arguments?
In C 17, constexpr functions like the below snippet are invalid:
<code class="cpp">constexpr int foo(int i) { return std::integral_constant<int, i>::value; }</code>
Despite foo's evaluation at compile-time, the compiler requires it to be executable at runtime, hindering template instantiation.
C 20 introduces consteval functions, which enforce compile-time evaluation. One may wonder if this allows code like the following:
<code class="cpp">consteval int foo(int i) { return std::integral_constant<int, i>::value; }</code>
The answer is no.
The paper's potential changes cannot alter the singular typing of non-template function definitions. Furthermore, if this code were valid, it would open up the possibility of declaring variables of type std::integral_constant
The paper also illustrates that parameters will not be treated as core constant expressions through an example:
<code class="cpp">consteval int sqrsqr(int n) { return sqr(sqr(n)); // Not a constant-expression at this point, but that's okay. }</code>
In essence, function parameters will always lack constant expression status due to potential typing inconsistencies.
The above is the detailed content of Can Consteval Functions Allow Template Parameters Reliant on Function Arguments?. For more information, please follow other related articles on the PHP Chinese website!