Comparing constexpr function parameter in constexpr-if condition causes error

前端 未结 2 635
轮回少年
轮回少年 2020-12-12 02:41

I\'m trying to compare a function parameter inside a constexpr-if statement.

Here is a simple example:

constexpr bool test_int(const int i) {
  if c         


        
2条回答
  •  旧时难觅i
    2020-12-12 03:09

    From constexpr if:

    In a constexpr if statement, the value of condition must be a contextually converted constant expression of type bool.

    Then, from constant expression:

    Defines an expression that can be evaluated at compile time.

    Obviously, i == 5 is not a constant expression, because i is a function parameter which is evaluated at run time. That is why the compiler complains.

    When you use a function:

    constexpr bool test_int_no_if(const int i) { return (i == 5); }
    

    then it might be evaluated during the compile time depending on whether it's parameter is known at compile time or not.

    If i is defined like:

    constexpr int i = 5;
    

    then the value of i is known during the compile time and test_int_no_if might be evaluated during the compile too making it possible to call it inside static_assert.

    Also note, that marking function parameter as const does not make it a compile time constant. It just means that you cannot change the parameter inside the function.

提交回复
热议问题