Home > Backend Development > C++ > Why Can't I Use a Function Parameter in a `constexpr` Function as a Constant Expression?

Why Can't I Use a Function Parameter in a `constexpr` Function as a Constant Expression?

Mary-Kate Olsen
Release: 2024-11-22 00:28:14
Original
548 people have browsed it

Why Can't I Use a Function Parameter in a `constexpr` Function as a Constant Expression?

Can't Use Function Parameter of a constexpr Function in a Constant Expression

The code snippet provided shows a constexpr function make_const and a function t1 that attempts to use make_const with a non-constant expression. This raises an error because i in t1 is not a constant expression.

A constexpr function, when given constant arguments, can be evaluated at compile time. However, if a non-constexpr parameter is passed to a constexpr function, it does not make that parameter a constant expression.

In the code below, t1 is a constexpr function, but make_const(i) inside t1 is not a constant expression because i is not a constant:

constexpr int t1(const int i)
{
    return make_const(i);
}
Copy after login
Copy after login

The updated code shows that t1 can be declared as constexpr and return the result of make_const:

constexpr int t1(const int i)
{
    return make_const(i);
}
Copy after login
Copy after login

However, the code below will still result in an error because do_something() is not a constant expression:

template<int i>
constexpr bool do_something(){
    return i;
}

constexpr int t1(const int i)
{
    return do_something<make_const(i)>();
}
Copy after login

To summarize, a constexpr function parameter must be a constant expression. If a non-constant parameter is passed, it does not become a constant expression within the constexpr function.

The above is the detailed content of Why Can't I Use a Function Parameter in a `constexpr` Function as a Constant Expression?. For more information, please follow other related articles on the PHP Chinese website!

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