The provided code demonstrates an attempt to utilize the return value of a constexpr function make_const within a constant expression, but it encounters an error.
static constexpr int make_const(const int i) { return i; } void t1(const int i) { constexpr int ii = make_const(i); // Error occurs here (i is not a constant expression) std::cout << ii; } int main() { t1(12); // Call the function }
A constexpr function, contrary to popular belief, does not magically make its parameters evaluated at compile-time. Instead, it allows for the propagation of constexprness from its input arguments to its output. However, in the given code, the function parameter i is not a constexpr, so the constexpr function make_const cannot convert it into one.
The error arises because the subsequent assignment constexpr int ii = make_const(i) attempts to declare a constexpr variable (ii) initialized with the result of a non-constexpr expression (make_const(i)). This is not allowed, as constexpr variables must always be initialized with constexpr expressions.
A constexpr function exhibits two key characteristics:
To resolve the error, one can ensure that the function parameter itself is constexpr. This can be achieved by modifying the function declaration to:
constexpr int make_const(constexpr int i) { return i; }
This alteration guarantees that the function can effectively convert its constexpr inputs into constexpr outputs, enabling the intended use of the function within a constant expression.
In the alternative code examples provided, the function make_const can be invoked as a constexpr expression in t1 since its parameters are now constexpr. However, attempting to pass the result of a non-constexpr expression (such as a runtime variable) into the function will still result in an error, as the function requires constexpr arguments for its constexpr execution.
以上是為什麼我不能在常數表達式中使用 `constexpr` 函數的函數參數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!