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 constexpr
ness 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).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…