在函數定義關鍵字constexpr
告訴該功能可以被在編譯時,如果所有的參數和變量在編譯時知道自己執行的編譯器。然而,沒有這樣的保證,例如當在運行時可以知道一些值時,在這種情況下該功能將在運行時被執行。
然而,它無關純或不純,因爲這些條款意味着輸出取決於輸入唯一的,無論你有多少次調用函數的輸入參數相同的值,每次輸出都是相同的,而不管它是在編譯時還是運行時計算的。
實施例,
constexpr int add(int a, int b) { return a + b; } //pure!
const int a = 2, b = 3; //const
int c = 2, d = 3; //non-const
//we may read update c and d here!
const int v1 = add(2,3); //computed at compile-time
const int v2 = add(a,3); //computed at compile-time
const int v3 = add(2,b); //computed at compile-time
const int v4 = add(a,b); //computed at compile-time
const int v3 = add(c,3); //computed at runtime
const int v3 = add(c,b); //computed at runtime
const int v3 = add(a,d); //computed at runtime
const int v3 = add(c,d); //computed at runtime
注意,這裏add
爲純函數不論它是在編譯時或運行時計算的。
rand()是一個constexpr? – Yakk
不,它不是,這就是爲什麼我把;)在評論 – NoSenseEtAl