C++核心準則邊譯邊學-F.4 如果函數(shù)有可能需要編譯時計算,將它定義...

F.4: If a function may have to be evaluated at compile time, declare it constexpr(如果函數(shù)有可能需要編譯時計算,將它定義為constexpr)
關(guān)于constexpr的基礎(chǔ)知識,可以參照以下鏈接:
https://mp.weixin.qq.com/s/Y_pEIVO8H6u-fpPczJU5Mw
Reason(原因)
constexpr is needed to tell the compiler to allow compile-time evaluation.
希望告訴編譯器允許編譯時計算的時候需要使用constexpr。
Example(示例)
The (in)famous factorial:
以下是(非)著名的階乘算法:
constexpr int fac(int n){constexpr int max_exp = 17; // constexpr enables max_exp to be used in ExpectsExpects(0 <= n && n < max_exp); // prevent silliness and overflowint x = 1;for (int i = 2; i <= n; ++i) x *= i;return x;}
This is C++14.
For C++11, use a recursive formulation of fac().
這是C++14中的做法。對于C++11,使用遞歸形式的fac()。
Note(注意)
constexpr does not guarantee compile-time evaluation;
it just guarantees that the function can be evaluated at compile time
for constant expression arguments if the programmer requires it or the
compiler decides to do so to optimize.
常數(shù)表達式不會保證編譯時計算;它只是表示如果函數(shù)的參數(shù)為常數(shù)表達式,而且程序員希望或者編譯器判斷這么做的情況下可以在編譯時計算。
constexpr int min(int x, int y) { return x < y ? x : y; }void test(int v){int m1 = min(-1, 2); // probably compile-time evaluationconstexpr int m2 = min(-1, 2); // compile-time evaluationint m3 = min(-1, v); // run-time evaluationconstexpr int m4 = min(-1, v); // error: cannot evaluate at compile time}
Note(注意)
Don't try to make all functions constexpr.
Most computation is best done at run time.
不要試圖將所有的函數(shù)指定為constexpr。大部分計算更適合在執(zhí)行時進行。
Note(注意)
Any API that may eventually depend on high-level run-time configuration or
business logic should not be made constexpr. Such customization can not be
evaluated by the compiler, and any constexpr functions that depended upon
that API would have to be refactored or drop constexpr.
任何最終依靠高層次實時配置或者商業(yè)邏輯的API都不應(yīng)該被指定為constexpr。這樣的定制無法在編譯時進行,依賴這個API的任何constexpr函數(shù)必須重構(gòu)或者去掉constexpr屬性。
Enforcement(實施建議)
Impossible and unnecessary.
The compiler gives an error if a non-constexpr function is called where a constant is required.
不可能也不必要。如果需要一個常量結(jié)果而非constexpr函數(shù)被調(diào)用的話,編譯器會報錯。
