The body of constexpr function not a return-statement

前端 未结 2 1840
栀梦
栀梦 2021-02-01 08:56

In the following program, I have added an explicit return statement in func(), but the compiler gives me the following error:

m.cpp: In         


        
2条回答
  •  误落风尘
    2021-02-01 09:29

    C++11's constexpr functions are more restrictive than that.

    From cppreference:

    the function body must be either deleted or defaulted or contain only the following:

    • null statements (plain semicolons)
    • static_assert declarations
    • typedef declarations and alias declarations that do not define classes or enumerations
    • using declarations
    • using directives
    • exactly one return statement.

    So you can say this instead:

    constexpr int func (int x) { return x < 0 ? -x : x; }
    
    static_assert(func(42) == 42, "");
    static_assert(func(-42) == 42, "");
    
    int main() {}
    

    Note that this restriction was lifted in C++14.

提交回复
热议问题