首頁 > 後端開發 > C++ > 為什麼我無法將非 Constexpr 參數傳遞給 Constexpr 函數?

為什麼我無法將非 Constexpr 參數傳遞給 Constexpr 函數?

Susan Sarandon
發布: 2024-11-15 08:57:02
原創
608 人瀏覽過

Why Can't I Pass Non-Constexpr Arguments to a Constexpr Function?

Limitations of Constexpr Function Parameters in Constant Expressions

Consider the code snippet:

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

Error Details

The code triggers an error when attempting to initialize ii with make_const(i) because i is not a constant expression. This is because:

  • A constexpr variable is a variable with a value guaranteed to be available at compile time.
  • A constexpr function is a function that evaluates at compile time when provided with constexpr arguments.

Passing a non-constexpr parameter to a constexpr function does not result in a constexpr output. However, the constexpr function can inherit and propagate the constexprness of its input parameters.

Allowed Scenarios

The following code works because both t1() and make_const() are constexpr functions with constexpr parameters:

constexpr int t1(const int i)
{
    return make_const(i);
}
登入後複製

Limitations

The following code fails because do_something() is not a constexpr function, even though make_const() is:

template<int i>
constexpr bool do_something(){
    return i;
}

constexpr int t1(const int i)
{
    return do_something<make_const(i)>();   // error occurs here (i is not a constant expression)
}
登入後複製

Conclusion

Understanding the distinction between constexpr functions and variables is crucial to avoid such errors. Constexpr functions offer the flexibility of being evaluated at both compile-time and run-time, but only with constexpr arguments.

以上是為什麼我無法將非 Constexpr 參數傳遞給 Constexpr 函數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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