Home > Backend Development > C++ > body text

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

Linda Hamilton
Release: 2024-10-23 16:43:02
Original
477 people have browsed it

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!