Home  >  Article  >  Backend Development  >  Can Consteval Functions Enable Template Parameter Dependence on Function Arguments in C 20?

Can Consteval Functions Enable Template Parameter Dependence on Function Arguments in C 20?

Linda Hamilton
Linda HamiltonOriginal
2024-10-23 16:43:02479browse

Can Consteval Functions Enable Template Parameter Dependence on Function Arguments in C  20?

Consteval Functions and Template Parameter Dependence on Function Arguments

In C 17, using a function that returns a constant directly within a template parameter declaration is prohibited due to runtime execution constraints. With the introduction of consteval functions in C 20, these constraints are expected to be removed. However, will this enable the following code to compile successfully?

<code class="cpp">consteval int foo(int i) {
    return std::integral_constant<int, i>::value;
}</code>

No.

Despite the consteval function's compile-time evaluation requirement, the function definition itself only undergoes typing once. As such, function parameters will never be treated as core constant expressions due to the potential for typing discrepancies.

This limitation is further emphasized in the C 20 proposal, which explicitly excludes parameters from being considered constant expressions in its 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>

Therefore, consteval functions do not allow template parameters to depend on function arguments because parameters lack the necessary typing guarantees as constant expressions.

The above is the detailed content of Can Consteval Functions Enable Template Parameter Dependence on Function Arguments in C 20?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn