首頁 > 後端開發 > C++ > 主體

為什麼我不能在常數表達式中使用 `constexpr` 函數的函數參數?

Mary-Kate Olsen
發布: 2024-11-14 15:06:02
原創
968 人瀏覽過

Why Can't I Use a Function Parameter of a `constexpr` Function in a Constant Expression?

Can't Use Function Parameter of a constexpr Function in a Constant Expression

Problem Introduction and Code Example

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
}
登入後複製

Explanation and Approach

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.

Understanding constexpr Functions

A constexpr function exhibits two key characteristics:

  • Documentation: It indicates to the compiler that the function, if given constexpr arguments and executing without undefined behavior, can be evaluated at compile time.
  • Instruction: It prompts the compiler to evaluate the function at compile time if it is used in specific contexts that require constexpr expressions.

Resolution

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板