简体   繁体   中英

C++11 constexpr function pass parameter

Consider the following code:

static constexpr int make_const(const int i){
    return i;
}

void t1(const int i)
{
    constexpr int ii = make_const(i);  // error occurs here (i is not a constant expression)
    std::cout<<ii;
}

int main()
{
   t1(12);
}

Why I have an error on make_const call?


UPDATE

But this one works:

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

However, this not:

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

constexpr int t1(const int i)
{
    return do_something<make_const(i)>();   // error occurs here (i is not a constant expression)
}

A constexpr function and a constexpr variable are related, but different things.

A constexpr variable is a variable whose value is guaranteed to be available at compile time.

A constexpr function is a function that, if evaluated with constexpr arguments, and behaves "properly" during its execution, will be evaluated at compile time.

If you pass a non- constexpr int to a constexpr function, it will not magically make it evaluated at compile time. It will, however, be allowed to pass the constexpr ness of its input parameters through itself (normal functions cannot do this).

constexpr on functions is a mixture of documentation and restriction on how they are written and instructions to the compiler.

The reason behind this is to allow the same function to be evaluated both at compile time, and at run time. If passed runtime arguments, it is a runtime function. If passed constexpr arguments, it may be evaluated at compile time (and will be if used in certain contexts).

One important difference between const and constexpr is that a constexpr can be evaluated at compile time.

By writing constexpr int ii = make_const(i); you are telling the compiler that the expression is to be evaluted at compile time. Since i is evaluted at run-time, the compiler is unable to do this and gives you an error.

Because t1() is not a constexpr function, the parameter i is a runtime variable... which you can't pass to a constexpr function. Constexpr expects the parameter to be known at compile time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM