constexpr 函数增强
C++17 对 constexpr 的增强
C++11 引入了 constexpr 关键字,但对 constexpr 函数的限制非常严格——函数体只能包含一条 return 语句。C++14 放宽了限制,允许使用 if、for、局部变量等。C++17 在此基础上进一步增强,主要体现在两个方面:
- constexpr lambda 表达式:lambda 可以声明为
constexpr,也可以在 constexpr 上下文中隐式成为 constexpr - 标准库的 constexpr 化:
std::array的大部分操作、std::begin/std::end等范围访问函数都变成了 constexpr
constexpr 的演进
| 版本 | constexpr 函数可以包含的内容 |
|---|---|
| C++11 | 只能有一条 return 语句(加 static_assert、using 等声明) |
| C++14 | if、switch、for、while、局部变量、多条 return |
| C++17 | lambda 表达式、标准库容器操作(std::array)、if constexpr |
| C++20 | try-catch、虚函数、动态内存分配、std::vector/std::string |
基本示例
#include <iostream>
#include <array>
#include <algorithm>
#include <type_traits>
#include <numeric>
// ============================
// 示例1:constexpr lambda(C++17 新增)
// ============================
void constexpr_lambda_demo() {
// lambda 可以显式声明为 constexpr
constexpr auto square = [](int x) constexpr {
return x * x;
};
// 在编译期使用
static_assert(square(5) == 25);
constexpr int result = square(7);
std::cout << "square(7) = " << result << std::endl; // 49
// lambda 也可以隐式成为 constexpr(满足条件时自动推导)
auto add = [](int a, int b) { return a + b; };
// 虽然没写 constexpr,但它满足条件,可以在编译期使用
static_assert(add(3, 4) == 7);
// 带捕获的 constexpr lambda
constexpr int base = 100;
constexpr auto offset = [base](int x) { return base + x; };
static_assert(offset(42) == 142);
std::cout << "constexpr lambda 测试通过" << std::endl;
}
// ============================
// 示例2:constexpr 函数中使用 if 和循环(C++14 起,C++17 增强)
// ============================
// 编译期计算阶乘
constexpr long long factorial(int n) {
long long result = 1;
for (int i = 2; i <= n; ++i) {
result *= i;
}
return result;
}
// 编译期计算斐波那契数
constexpr int fibonacci(int n) {
if (n <= 1) return n;
int a = 0, b = 1;
for (int i = 2; i <= n; ++i) {
int temp = a + b;
a = b;
b = temp;
}
return b;
}
// 编译期判断素数
constexpr bool is_prime(int n) {
if (n < 2) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) return false;
}
return true;
}
void compile_time_calc_demo() {
// 全部在编译期计算
static_assert(factorial(10) == 3628800);
static_assert(fibonacci(10) == 55);
static_assert(is_prime(97));
static_assert(!is_prime(100));
// 作为模板参数
std::array<int, fibonacci(7)> arr{}; // std::array<int, 13>
std::cout << "arr 大小: " << arr.size() << std::endl;
std::cout << "编译期计算测试通过" << std::endl;
}
// ============================
// 示例3:constexpr std::array 操作(C++17 增强)
// ============================
constexpr std::array<int, 5> make_squares() {
std::array<int, 5> result{}; // C++17 起 std::array 的操作是 constexpr
for (int i = 0; i < 5; ++i) {
result[i] = (i + 1) * (i + 1); // operator[] 是 constexpr
}
return result;
}
constexpr int sum_array(const std::array<int, 5>& arr) {
int total = 0;
// C++17 起 std::array::begin/end 是 constexpr
for (const auto& x : arr) {
total += x;
}
return total;
}
void constexpr_array_demo() {
constexpr auto squares = make_squares();
static_assert(squares[0] == 1);
static_assert(squares[4] == 25);
constexpr int total = sum_array(squares);
static_assert(total == 1 + 4 + 9 + 16 + 25); // 55
std::cout << "squares: ";
for (auto x : squares) std::cout << x << " ";
std::cout << std::endl;
std::cout << "总和: " << total << std::endl;
}
// ============================
// 示例4:constexpr 字符串处理(编译期)
// ============================
// 编译期计算字符串长度
constexpr std::size_t str_length(const char* s) {
std::size_t len = 0;
while (s[len] != '\0') {
++len;
}
return len;
}
// 编译期比较两个字符串
constexpr bool str_equal(const char* a, const char* b) {
while (*a && *b) {
if (*a != *b) return false;
++a;
++b;
}
return *a == *b;
}
// 编译期统计字符出现次数
constexpr int count_char(const char* s, char c) {
int count = 0;
while (*s) {
if (*s == c) ++count;
++s;
}
return count;
}
void constexpr_string_demo() {
static_assert(str_length("hello") == 5);
static_assert(str_equal("abc", "abc"));
static_assert(!str_equal("abc", "abd"));
static_assert(count_char("hello world", 'l') == 3);
std::cout << "编译期字符串处理测试通过" << std::endl;
}
// ============================
// 示例5:constexpr 与 if constexpr 配合
// ============================
template<typename T>
constexpr T absolute(T value) {
if constexpr (std::is_unsigned_v<T>) {
// 无符号类型直接返回
return value;
} else {
// 有符号类型取绝对值
return value < 0 ? -value : value;
}
}
template<typename T>
constexpr T clamp(T value, T low, T high) {
if (value < low) return low;
if (value > high) return high;
return value;
}
void constexpr_template_demo() {
static_assert(absolute(-42) == 42);
static_assert(absolute(42u) == 42u);
static_assert(clamp(15, 0, 10) == 10);
static_assert(clamp(-5, 0, 10) == 0);
static_assert(clamp(5, 0, 10) == 5);
std::cout << "constexpr 模板函数测试通过" << std::endl;
}
int main() {
std::cout << "=== constexpr lambda ===" << std::endl;
constexpr_lambda_demo();
std::cout << "\n=== 编译期计算 ===" << std::endl;
compile_time_calc_demo();
std::cout << "\n=== constexpr array ===" << std::endl;
constexpr_array_demo();
std::cout << "\n=== 编译期字符串 ===" << std::endl;
constexpr_string_demo();
std::cout << "\n=== constexpr 模板 ===" << std::endl;
constexpr_template_demo();
return 0;
}C++17 constexpr lambda 的细节
#include <iostream>
#include <type_traits>
// constexpr lambda 可以作为模板参数
template<auto F>
constexpr auto apply_twice(int x) {
return F(F(x));
}
// constexpr lambda 可以赋给 constexpr 变量
constexpr auto double_it = [](int x) { return x * 2; };
// 闭包类型是字面量类型(如果捕获的成员都是字面量类型)
static_assert(std::is_literal_type_v<decltype(double_it)>); // C++17 中成立
void lambda_details() {
// constexpr lambda 既可以编译期用也可以运行时用
constexpr int ct = double_it(21); // 编译期
int rt = double_it(21); // 运行时
static_assert(ct == 42);
std::cout << "运行时: " << rt << std::endl;
// 泛型 constexpr lambda
constexpr auto max = [](auto a, auto b) { return a > b ? a : b; };
static_assert(max(3, 5) == 5);
static_assert(max(3.14, 2.71) == 3.14);
}
int main() {
lambda_details();
return 0;
}适用场景
- 编译期查找表和常量数组的生成
- 编译期数学计算(阶乘、斐波那契、组合数等)
- 编译期字符串处理和验证
- 模板元编程中替代复杂的递归模板
- 配合
static_assert做编译期校验 - 游戏开发中的编译期资源哈希计算
常见问题
constexpr 函数一定在编译期执行吗?
不一定。constexpr 函数在需要编译期结果的上下文中(constexpr 变量初始化、static_assert、模板参数、std::array 大小等)才保证编译期执行。在其他上下文中,编译器可能在编译期执行也可能在运行时执行,取决于优化。
constexpr 函数和 inline 有什么关系?
constexpr 函数隐含 inline。所以 constexpr 函数可以定义在头文件中而不违反 ODR(One Definition Rule)。
为什么 C++17 的 constexpr std::array 很重要?
在 C++14 中,std::array 的 operator[] 不是 constexpr 的(const 版本是,但非 const 版本不是)。这意味着你无法在编译期修改 array 的元素。C++17 让非 const 的 operator[] 也成为 constexpr,所以可以在 constexpr 函数中构建和修改 array。
constexpr lambda 和普通 lambda 有什么区别?
在 C++17 中,如果 lambda 满足 constexpr 函数的所有要求,它会自动成为 constexpr,不需要显式标注。显式写 constexpr 的作用是:如果 lambda 不满足 constexpr 要求,编译器会报错而不是默默退化为普通 lambda。
注意事项
- constexpr 函数不能包含
asm声明、goto语句、static或thread_local变量(C++17) - constexpr 函数不能调用非 constexpr 函数(在编译期求值时)
- C++17 中 constexpr 函数仍不能使用 try-catch(C++20 才允许)
- C++17 中 constexpr 函数不能动态分配内存(C++20 才允许)
- constexpr lambda 捕获的变量必须是字面量类型
std::is_literal_type在 C++17 中已弃用(C++20 移除),但字面量类型的概念仍然存在
编译器支持情况
| 特性 | GCC | Clang | MSVC |
|---|---|---|---|
| constexpr lambda | 7.0 | 5.0 | 19.11 (VS 2017 15.3) |
| constexpr std::array | 7.0 | 6.0 | 19.14 (VS 2017 15.7) |
| if constexpr | 7.0 | 3.9 | 19.11 (VS 2017 15.3) |
总结
C++17 对 constexpr 的增强主要集中在两个方面:一是 constexpr lambda,让 lambda 可以参与编译期计算;二是标准库的 constexpr 化,让 std::array 等容器可以在编译期构建和操作。配合 C++14 已有的 constexpr 放宽(if、for、局部变量等),C++17 的 constexpr 已经可以处理相当复杂的编译期计算——生成查找表、处理字符串、构建数据结构。constexpr 函数写起来和普通函数几乎一样,但可以在编译期执行,把运行时计算提前到编译期完成,这对性能关键的应用很有价值。