Home  >  Article  >  Backend Development  >  Can Consteval Functions Allow Template Parameters Reliant on Function Arguments?

Can Consteval Functions Allow Template Parameters Reliant on Function Arguments?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-24 01:35:01390browse

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, which seems highly restrictive in terms of the One Definition Rule (ODR).

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!

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