Home  >  Article  >  Backend Development  >  Can Function Parameters Be Template Dependent Because of Consteval Functions?

Can Function Parameters Be Template Dependent Because of Consteval Functions?

Linda Hamilton
Linda HamiltonOriginal
2024-10-23 17:46:41151browse

Can Function Parameters Be Template Dependent Because of Consteval Functions?

Can Consteval Functions Enable Template Parameters Dependent on Function Arguments?

In C 17, defining a constexpr function that returns a compile-time constant may seem logical, but it's prohibited. The compiler demands runtime execution instructions, preventing template instantiation involving such functions.

C 20 introduces consteval functions, ensuring their evaluation at compile time. With this, many expected this constraint to vanish, allowing code like:

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

However, the answer is still a resolute no.

Despite the paper's potential changes, the fact remains that non-template function definitions are typed only once. Permitting such code would potentially enable the declaration of variables with non-ODR-friendly types like std::integral_constant, which is highly undesirable.

The paper also implies that parameters shouldn't be treated as core constant expressions. One example illustrates this:

<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 summary, function parameters will not evolve into constant expressions due to potential typing inconsistencies.

The above is the detailed content of Can Function Parameters Be Template Dependent Because of Consteval Functions?. 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