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

Can Consteval Functions Allow Template Parameters Reliant on Function Arguments?

Mary-Kate Olsen
Release: 2024-10-24 01:35:01
Original
474 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template