C++11 constexpr function pass parameter

前端 未结 3 1630
旧时难觅i
旧时难觅i 2020-12-03 08:31

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);  //          


        
相关标签:
3条回答
  • 2020-12-03 08:54

    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.

    0 讨论(0)
  • 2020-12-03 08:55

    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.

    0 讨论(0)
  • 2020-12-03 09:14

    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 constexprness 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).

    0 讨论(0)
提交回复
热议问题