A constexpr
function implies that it is possible to evaluate the value of the function at compile time. Since this is possible for the input true
the function is a valid constexpr
. Remember that a constexpr
function can have an address just as a regular function, it does not need to be compile time, only when used as a compile time function (which you do not in your example).
As mentioned on the constexpr
page on cppreference:
A constexpr function must satisfy the following requirements:
- it must not be virtual
- its return type must be LiteralType
- each of its parameters must be LiteralType
- there exists at least one set of argument values such that an invocation of the function could be an evaluated subexpression of a core constant expression (for constructors, use in a constant initializer is sufficient) (since C++14). No diagnostic is required for a violation of this bullet. (Emphasis mine)
Your function fulfils all of the above requirements: it is not virtual, it returns a literal type, the parameter is literal. And more interestingly last bullet point: there exists at least one set of argument values for which the function is actually fully compile time. (hence my emphasis of the last bullet)
As W.F. mentioned in the comments, the function can be used compile time, but only for valid inputs, that is, inputs that does not lead to a sub expression that is not compile time constant. So the input true
will work, but false
will not since it will lead to bla
being evaluated.
This is also stated in the standard: §10.1.5.5:
For a constexpr function or constexpr constructor that is neither defaulted nor a template, if no argument values exist such that an invocation of the function or constructor could be an evaluated subexpression of a core constant expression (8.20), or, for a constructor, a constant initializer for some object (6.6.2), the program is ill-formed, no diagnostic required.
constexpr int f(bool b)
{ return b ? throw 0 : 0; } // OK
constexpr int f()
{ return f(true); } // ill-formed, no diagnostic required
See the examples from the standard document in particular.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…