Constexpr 函數 (C++11)
附註: IBM 在批准之前支援 C++11的選定特性,稱為 C++0x 。 IBM 將繼續開發並實作此標準的特性。 語言層次的實作是以 IBM的標準解譯為基礎。 在 IBM的所有 C++11 特性實作完成 (包括支援新的 C++11 標準程式庫) 之前,實作可能會在不同版本之間變更。 IBM 不會嘗試維護程式碼、二進位或清單及其他編譯器介面中的相容性,以及舊版 IBM的新 C++11 特性實作。
以宣告的非建構子函數constexpr指定元constexpr功能。 Aconstexpr函數是可以在常數表示式內呼叫的函數。
Aconstexpr函數必須滿足下列條件:
- 它不是虛擬。
- 其傳回類型是文字類型。
- 其每一個參數都必須是文字類型。
- 當起始設定回覆值時,每一個建構子呼叫和隱含轉換在常數表示式中都是有效的。
- 它的功能體是= delete或=
default; 否則,其函數主體必須只包含下列陳述式:
- null陳述式
- static_assert宣告
- typedef未定義類別或列舉的宣告
- using指引
- using宣告
- 一個return陳述式
當宣告非建構子的非靜態成員函數時,constexpr指定元,該成員函數是常數,且constexpr指定元對函數類型沒有其他作用。 該函數所屬的類別必須是文字類型。
下列範例示範的用法constexpr功能:
const int array_size1 (int x) {
return x+1;
}
// Error, constant expression required in array declaration
int array[array_size1(10)];
constexpr int array_size2 (int x) {
return x+1;
}
// OK, constexpr functions can be evaluated at compile time
// and used in contexts that require constant expressions.
int array[array_size2(10)];
struct S {
S() { }
constexpr S(int) { }
constexpr virtual int f() { // Error, f must not be virtual.
return 55;
}
};
struct NL {
~NL() { } // The user-provided destructor (even if it is trivial)
// makes the type a non-literal type.
};
constexpr NL f1() { // Error, return type of f1 must be a literal type.
return NL();
}
constexpr int f2(NL) { // Error, the parameter type NL is not a literal type.
return 55;
}
constexpr S f3() {
return S();
}
enum { val = f3() }; // Error, initialization of the return value in f3()
// uses a non-constexpr constructor.
constexpr void f4(int x) { // Error, return type should not be void.
return;
}
constexpr int f5(int x) { // Error, function body contains more than return statement.
if (x<0)
x = -x;
return x;
}
當函數範本宣告為constexpr函數,如果實例化所產生的函數不符合constexpr功能,constexpr會忽略指定元。 例如:
template <class C> constexpr NL f6(C c) { // OK, the constexpr specifier ignored
return NL();
}
void g() {
f6(55); // OK, not used in a constant expression
}
呼叫constexpr函數會產生相同的結果,作為對對等非constexpr所有方面的功能,除了呼叫constexpr函數可以出現在常數表示式中。
Aconstexprfunction is implicitly inline.
Themain無法以constexpr指定元。