"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Can template parameters in C++20 Consteval function depend on function parameters?

Can template parameters in C++20 Consteval function depend on function parameters?

Posted on 2025-04-17
Browse:113

Can Template Parameters Depend on Function Arguments in C  20 Consteval Functions?

Consteval Functions and Template Parameters Dependent on Function Arguments

In C 17, a template parameter cannot depend on a function argument because the compiler still needs to generate runtime instructions for non-constexpr functions, even if they are evaluated at compile-time.

C 20 Consteval Functions

C 20 introduces consteval functions, which must be evaluated at compile-time, removing the runtime constraint. However, the question remains: does this mean template parameters can now depend on function arguments?

No Allowances for Dependent Template Parameters

Despite the introduction of consteval functions, the answer is no. The paper acknowledges that parameters are not intended to be treated as core constant expressions. This is due to potential typing discrepancies, as demonstrated by the example in the paper:

consteval int sqrsqr(int n) {
  return sqr(sqr(n)); // Not a constant-expression at this  point,
}                     // but that's okay.

Therefore, function parameters will never be considered constant expressions, preventing template parameters from being dependent on them.

Release Statement This article is reproduced on: 1729672748 If there is any infringement, please contact [email protected] to delete it.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3