A constexpr function is not required to return a constant expression?

后端 未结 2 613
后悔当初
后悔当初 2021-01-08 00:56

C++ Primer (5th edition) on page 240 has a note stating:

\"A constexpr function is not required to return a constant ex

2条回答
  •  再見小時候
    2021-01-08 01:28

    A (non-template) constexpr function must have at least one execution path that returns a constant expression; formally, there must exist argument values such that "an invocation of the function [...] could be an evaluated subexpression of a core constant expression" ([dcl.constexpr]/5). For example (ibid.):

    constexpr int f(bool b) { return b ? throw 0 : 0; }     // OK
    constexpr int f() { return f(true); }     // ill-formed, no diagnostic required
    

    Here int f(bool) is allowed to be constexpr because its invocation with argument value false returns a constant expression.

    It is possible to have a constexpr function that cannot ever return a constant expression if it is a specialization of a function template that could have at least one specialization that does return a constant expression. Again, with the above:

    template constexpr int g() { return f(B); }    // OK
    constexpr int h() { return g(); }    // ill-formed, no diagnostic required
    

提交回复
热议问题