[英]Why is `constexpr` part of the C++14 template prototype for `std::max()`?
根據 cplusplus.com,這里, std::max()
的默認 C++11 原型是:
template <class T>
const T& max(const T& a, const T& b);
在 C++14 版本中,添加了constexpr
:
template <class T>
constexpr const T& max(const T& a, const T& b);
為什么constexpr
在這里,它添加了什么?
我認為我的問題不是這個問題的重復( `constexpr` 和 `const` 之間的區別),因為我問的是constexpr
的一個非常具體的用法,而那個問題是問“告訴我你對 const 和 constexpr 的了解”。 很難從這些大量答案中挖掘出具體的用法,因為其他問題的針對性和針對性不夠強,無法將答案直接推向我的問題。
這意味着 function 可以在常量表達式中使用,例如:
constexpr int f = max(3, 4);
保證f
在編譯時被評估。
Note that a function marked constexpr
may have both compile-time and run-time cases depending on the function arguments (and template parameters if it is a function template). 它必須至少有 1 個編譯時用例。
自 C++11 以來,許多標准庫函數都添加了constexpr
。
constexpr
向編譯器指示函數的結果可以在編譯時計算(假設參數在編譯時也是已知的)。 我認為這個主題很好地總結了你想知道的內容: `constexpr` 和 `const` 之間的區別
我正在做一些閱讀,在這種情況下,它看起來不是返回類型的修飾符,而是 function 本身的修飾符。 constexpr
說max()
是一個constexpr
function。 const T&
部分表示 function 返回對類型T
的const
引用,而constexpr
部分再次修改 function 本身。
This reference ( https://en.cppreference.com/w/cpp/language/constexpr ) indicates through its example that a constexpr
function is a function which possibly can be evaluated at compile-time, but if not at compile-time,它將像任何其他正常的 function 一樣在運行時進行評估。
來自上述參考的代碼片段(添加了星號):
constN<factorial(4)> out1; // computed at ***compile time***
volatile int k = 8; // disallow optimization using volatile
std::cout << k << "! = " << factorial(k) << '\n'; // computed at ***run time***
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.