consteval
说明符 (C++20 起)
来自 cppreference.cn
consteval
- 指定函数为立即函数,即对函数的每次调用都必须产生编译时常量
内容 |
[编辑] 解释
consteval
说明符声明函数或函数模板为立即函数,即每次对该函数的潜在求值调用都必须(直接或间接地)产生编译时常量表达式。
立即函数是constexpr 函数,并受制于其可能的要求。与 constexpr
相同,consteval
说明符隐含 inline
。但是,它不能应用于析构函数、分配函数或解分配函数。
指定 consteval
的函数或函数模板声明不得同时指定 constexpr
,并且该函数或函数模板的任何重新声明也必须指定 consteval
。
在最内层非块作用域不是立即函数的函数形参作用域的立即函数的潜在求值调用 或 consteval if 语句 的真分支(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
[编辑] 注解
特性测试宏 | 值 | Std | 特性 |
---|---|---|---|
__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) |
断言变量具有静态初始化,即零初始化和常量初始化 |
常量表达式 | 定义了可以在编译时求值的表达式 |