consteval
說明符 (C++20 起)
來自 cppreference.com
consteval
- 指定函式為立即函式,即對該函式的每次呼叫都必須產生一個編譯時常量。
目錄 |
[編輯] 解釋
consteval
說明符宣告函式或函式模板為立即函式,即對該函式的每個潛在求值呼叫都必須(直接或間接)產生一個編譯時常量表達式。
立即函式是constexpr 函式,並受其相應要求的約束。與 constexpr
相同,consteval
說明符暗示 inline
。但是,它不能應用於解構函式、分配函式或釋放函式。
指定 consteval
的函式或函式模板宣告不能同時指定 constexpr
,並且該函式或函式模板的任何重新宣告也必須指定 consteval
。
對立即函式的潛在求值呼叫,如果其最內層非塊作用域不是立即函式的函式引數作用域或 consteval if 語句 的 true 分支(C++23 起),則必須產生一個常量表達式;這種呼叫被稱為立即呼叫。
consteval int sqr(int n) { return n*n; } constexpr int r = sqr(100); // OK int x = 100; int r2 = sqr(x); // Error: Call does not produce a constant consteval int sqrsqr(int n) { return sqr(sqr(n)); // Not a constant expression at this point, but OK } constexpr int dblsqr(int n) { return 2 * sqr(n); // Error: Enclosing function is not consteval // and sqr(n) is not a constant }
表示立即函式的識別符號表示式只能出現在立即呼叫的子表示式中或立即函式上下文中(即上述上下文,其中對立即函式的呼叫無需是常量表達式)。可以獲取指向立即函式的指標或引用,但不能逃逸常量表達式求值。
consteval int f() { return 42; } consteval auto g() { return &f; } consteval int h(int (*p)() = g()) { return p(); } constexpr int r = h(); // OK constexpr auto e = g(); // ill-formed: a pointer to an immediate function is // not a permitted result of a constant expression
[編輯] 注意
功能測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_consteval |
201811L |
(C++20) | 立即函式 |
202211L |
(C++23) (DR20) |
使 consteval 傳播 |
[編輯] 關鍵詞
[編輯] 示例
執行此程式碼
#include <iostream> // This function might be evaluated at compile-time, if the input // is known at compile-time. Otherwise, it is executed at run-time. constexpr unsigned factorial(unsigned n) { return n < 2 ? 1 : n * factorial(n - 1); } // With consteval we enforce that the function will be evaluated at compile-time. consteval unsigned combination(unsigned m, unsigned n) { return factorial(n) / factorial(m) / factorial(n - m); } static_assert(factorial(6) == 720); static_assert(combination(4, 8) == 70); int main(int argc, const char*[]) { constexpr unsigned x{factorial(4)}; std::cout << x << '\n'; [[maybe_unused]] unsigned y = factorial(argc); // OK // unsigned z = combination(argc, 7); // error: 'argc' is not a constant expression }
輸出
24
[編輯] 參閱
constexpr 說明符(C++11) |
指定變數或函式的值可以在編譯時計算 |
constinit 說明符(C++20) |
斷言變數具有靜態初始化,即零初始化和常量初始化 |
常量表達式 | 定義可在編譯時求值的表示式 |