consteval 立即函数 ​

什么是 consteval ​

consteval 是 C++20 引入的关键字,用来声明"立即函数"(Immediate Function)。立即函数必须在编译期求值——如果编译器无法在编译期完成对它的调用求值,就会报编译错误。

consteval 和 constexpr 的区别在于强制性:constexpr 函数可以在编译期也可以在运行期求值(取决于上下文),而 consteval 函数只能在编译期求值,不会出现在最终的二进制代码中。

consteval vs constexpr vs const ​

特性constconstexprconsteval
引入版本C++98C++11C++20
用途标记变量只读允许编译期求值强制编译期求值
修饰函数不能能能
修饰变量能能不能
编译期求值保证无不保证(取决于上下文)保证
运行期调用不适用可以不可以(编译错误)
出现在二进制中不适用可能不会

语法 ​

cpp
consteval 返回类型 函数名(参数列表) {
    // 函数体——必须能在编译期求值
}

基本示例 ​

cpp
#include <iostream>
#include <cstdint>
#include <array>

// ============================
// 示例1:consteval 基本用法
// ============================

// 立即函数:必须在编译期求值
consteval int square(int x) {
    return x * x;
}

// constexpr 函数:可以在编译期也可以在运行期求值
constexpr int cube(int x) {
    return x * x * x;
}

void basic_demo() {
    // consteval 函数调用——编译期求值
    constexpr int s1 = square(5);       // 正确:编译期常量
    std::cout << "5^2 = " << s1 << std::endl;

    // 即使不赋给 constexpr 变量,也会在编译期求值
    std::cout << "6^2 = " << square(6) << std::endl;  // 编译期求值

    // 错误:不能用运行期变量调用 consteval 函数
    // int x = 7;
    // int s2 = square(x);  // 编译错误!x 不是编译期常量

    // constexpr 函数可以在运行期调用
    int y = 3;
    int c1 = cube(y);  // 正确:运行期求值
    std::cout << "3^3 = " << c1 << std::endl;
}

// ============================
// 示例2:编译期验证
// ============================

// 用 consteval 在编译期验证参数的合法性
consteval int safe_divide(int a, int b) {
    if (b == 0) {
        throw "除数不能为零";  // 编译期抛异常 → 编译错误
    }
    return a / b;
}

consteval std::uint32_t make_color(int r, int g, int b) {
    // 编译期范围检查
    if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) {
        throw "颜色分量必须在 0-255 范围内";
    }
    return (static_cast<std::uint32_t>(r) << 16) |
           (static_cast<std::uint32_t>(g) << 8)  |
           static_cast<std::uint32_t>(b);
}

void validation_demo() {
    constexpr int result = safe_divide(100, 4);  // 正确:25
    std::cout << "100 / 4 = " << result << std::endl;

    // constexpr int bad = safe_divide(100, 0);  // 编译错误:除数为零

    constexpr auto red = make_color(255, 0, 0);     // 正确
    constexpr auto green = make_color(0, 255, 0);   // 正确
    // constexpr auto bad_color = make_color(256, 0, 0);  // 编译错误:超出范围

    std::cout << "红色: 0x" << std::hex << red << std::endl;
    std::cout << "绿色: 0x" << green << std::dec << std::endl;
}

// ============================
// 示例3:编译期字符串处理
// ============================

// 编译期计算字符串长度
consteval std::size_t const_strlen(const char* str) {
    std::size_t len = 0;
    while (str[len] != '\0') {
        ++len;
    }
    return len;
}

// 编译期字符串哈希
consteval std::uint64_t const_hash(const char* str) {
    std::uint64_t hash = 5381;
    while (*str) {
        hash = hash * 33 + static_cast<unsigned char>(*str);
        ++str;
    }
    return hash;
}

void string_demo() {
    // 编译期计算字符串长度
    constexpr auto len = const_strlen("Hello, World!");
    std::cout << "长度: " << len << std::endl;  // 13

    // 编译期字符串哈希——可以用在 switch 中
    constexpr auto h1 = const_hash("hello");
    constexpr auto h2 = const_hash("world");
    std::cout << "hash(hello) = " << h1 << std::endl;
    std::cout << "hash(world) = " << h2 << std::endl;

    // 用编译期哈希做字符串 switch
    constexpr auto test_hash = const_hash("hello");
    switch (test_hash) {
        case const_hash("hello"):
            std::cout << "匹配 hello" << std::endl;
            break;
        case const_hash("world"):
            std::cout << "匹配 world" << std::endl;
            break;
    }
}

// ============================
// 示例4:consteval 与模板
// ============================

// consteval 函数模板
template<typename T>
consteval T compile_time_max(T a, T b) {
    return a > b ? a : b;
}

// 用 consteval 生成编译期查找表
consteval auto make_squares_table() {
    std::array<int, 16> table{};
    for (int i = 0; i < 16; ++i) {
        table[i] = i * i;
    }
    return table;
}

void template_demo() {
    constexpr auto m1 = compile_time_max(3, 7);     // int
    constexpr auto m2 = compile_time_max(3.14, 2.71); // double
    std::cout << "max(3,7) = " << m1 << std::endl;
    std::cout << "max(3.14,2.71) = " << m2 << std::endl;

    // 编译期生成的查找表
    constexpr auto squares = make_squares_table();
    for (int i = 0; i < 16; ++i) {
        std::cout << i << "^2=" << squares[i] << " ";
    }
    std::cout << std::endl;
}

// ============================
// 示例5:consteval 调用 constexpr
// ============================

// constexpr 辅助函数
constexpr int add(int a, int b) {
    return a + b;
}

// consteval 可以调用 constexpr 函数
consteval int compute(int a, int b, int c) {
    return add(add(a, b), c);  // 正确:consteval 可以调用 constexpr
}

// constexpr 函数不能在所有情况下调用 consteval 函数
// 只有在编译期上下文中才可以
constexpr int wrapper(int x) {
    // return square(x);  // 可能错误:constexpr 函数可能在运行期调用
    // 但如果总是在编译期上下文中调用 wrapper,某些编译器可能允许
    return x * x;  // 安全做法:不调用 consteval
}

void call_chain_demo() {
    constexpr int r = compute(1, 2, 3);
    std::cout << "compute(1,2,3) = " << r << std::endl;  // 6
}

int main() {
    std::cout << "=== 基本用法 ===" << std::endl;
    basic_demo();

    std::cout << "\n=== 编译期验证 ===" << std::endl;
    validation_demo();

    std::cout << "\n=== 字符串处理 ===" << std::endl;
    string_demo();

    std::cout << "\n=== 模板 ===" << std::endl;
    template_demo();

    std::cout << "\n=== 调用链 ===" << std::endl;
    call_chain_demo();

    return 0;
}

consteval 的调用规则 ​

调用方向是否允许说明
consteval 调用 consteval允许两者都是编译期
consteval 调用 constexpr允许constexpr 函数在编译期上下文中求值
constexpr 调用 consteval有条件只有当 constexpr 函数在编译期上下文中被调用时才行
普通函数调用 consteval有条件参数必须是编译期常量
consteval 调用普通函数不允许普通函数不能在编译期求值

适用场景 ​

  • 编译期参数验证(越界检查、空指针检查等)
  • 编译期查找表生成
  • 编译期字符串哈希(用于字符串 switch)
  • 类型安全的编译期常量工厂
  • 确保某些计算零运行时开销

常见问题 ​

consteval 函数的参数是 constexpr 吗?

不是。这一点可能让人意外——即使 consteval 函数只能在编译期调用,它的参数在函数体内部并不被视为 constexpr。这是标准为了一致性做的决定。但在 consteval 函数内部,对参数的操作仍然在编译期完成。

consteval 函数可以有副作用吗?

不能有运行期副作用(因为它不在运行期执行)。但可以有编译期的"副作用",比如通过 throw 触发编译错误来报告参数不合法。

consteval 函数可以是虚函数吗?

不能。consteval 函数不能是虚函数,因为虚函数的调用需要在运行期通过虚表解析。

consteval 函数可以获取地址吗?

不能。consteval 函数不存在于运行期,所以不能取它的地址,也不能赋值给函数指针。

consteval 和 constexpr 能互相替代吗?

不能完全替代。consteval 比 constexpr 更严格——所有 consteval 能做的事 constexpr 都能做(在编译期上下文中),但 consteval 强制了编译期求值。如果你需要一个函数在运行期和编译期都能用,选 constexpr;如果必须保证编译期求值,选 consteval。

注意事项 ​

  • consteval 函数只能在编译期调用,传入运行期变量会编译错误
  • consteval 函数不会出现在最终的二进制代码中
  • consteval 函数不能是虚函数
  • 不能获取 consteval 函数的地址
  • consteval 函数的参数在函数体内不是 constexpr
  • constexpr 函数调用 consteval 函数有限制(C++23 的 consteval 传播规则放宽了这个限制)
  • consteval 可以和模板一起使用

编译器支持情况 ​

编译器最低支持版本
GCC11.0
Clang14.0
MSVC19.29 (VS 2019 16.10)

总结 ​

consteval 声明的立即函数必须在编译期求值,如果做不到就报编译错误。和 constexpr 相比,consteval 提供了更强的保证——函数调用一定在编译期完成,不会产生任何运行期开销,也不会出现在最终二进制中。consteval 最实用的场景是编译期参数验证(通过 throw 触发编译错误报告非法参数)、编译期查找表生成、编译期字符串哈希等。它可以调用 constexpr 函数,但 constexpr 函数调用 consteval 函数有条件限制。选择 consteval 还是 constexpr 的原则很简单:如果函数必须在编译期执行,用 consteval;如果需要编译期和运行期都能用,用 constexpr。