前言
c++26 是 c++ 语言的下一个重要标准版本,已于 2025 年完成功能冻结。我们来看看 c++26 有哪些新特性。
一、三大核心特性
1.1 静态反射(static reflection)
静态反射是 c++26 最重磅的特性之一,在编译期能查询类型、成员、枚举值等结构信息,并把反射结果插入到代码中。
#include <meta> // 新的反射头文件
#include <string>
enum class color { red, green, blue };
// 将枚举转换为字符串
template <typename e>
requires std::is_enum_v<e>
constexpr std::string enum_to_string(e value) {
template for (constexpr auto e : std::meta::members_of(^e)) {
if (value == [:e:]) { // 反射表达式求值
return std::string(std::meta::name_of(e));
}
}
return "<unnamed>";
}
int main() {
static_assert(enum_to_string(color::red) == "red");
static_assert(enum_to_string(color::blue) == "blue");上述代码中:
^e:反射操作符,获取类型的元数据[:e:]:反射表达式求值,将元数据转换回实际值template for:编译期循环,遍历所有枚举成员
1.2 契约(contracts)
契约为函数添加前置条件(pre)、后置条件(post),增强可读性。
【前置条件在进入函数前检查,后置条件在函数退出时检查】
int divide(int a, int b)
[[pre: b != 0]] // 前置条件:除数不能为0
[[post r: r * b == a]] // 后置条件:结果验证 (返回值用r标记)
{
return a / b;
}
// 类不变式
class stack {
int size_ = 0;
int* data_ = nullptr;
public:
void push(int val)
[[pre: size_ < capacity()]] // 栈未满
[[post: size() == old size() + 1]] // 大小增加1
{
data_[size_++] = val;
}
int pop()
[[pre: size_ > 0]] // 栈非空
[[post: size() == old size() - 1]]
{
return data_[--size_];
}
};1.3 执行控制库(std::execution)
这是 c++26 的“异步执行标准框架”,用来抽象各种执行资源(如 线程池)上的任务调度。它是一个标准化的异步编程框架,用于管理异步执行。
#include <execution>
#include <iostream>
int main() {
auto sch = std::execution::get_scheduler(); // 获取默认调度器
// 1) 从调度器得到一个 sender
auto snd = std::execution::schedule(sch);
// 2) then 在其上接一个同步任务,返回 int
auto snd2 = std::execution::then(snd, [] {
std::cout << "hello from std::execution\n";
return 42;
});
// 3) 再接一个任务消费 int
auto snd3 = std::execution::then(snd2, [](int x) {
std::cout << "got " << x << "\n";
});
// 4) 提交并等待完成(具体细节略有出入,此处为示意)
std::execution::sync_wait(snd3);
}二、其他一些新特性
2.1 占位变量
c++26 引入无命名占位符"_",表示“不关心这个值”,可以多次使用。
auto [a, _, _] = std::tuple{1, 2.0, 'x'};
// _ 没有名字,不能用 _ 去读;只表示“占位”2.2 参数包索引
参数包索引(pack indexing),允许在包里直接用下标访问某个元素,而不用把整包展开再访问。
template<typename... ts>
constexpr auto first_plus_last(ts... values)
-> ts...[0] // 包的第 0 号类型作为返回类型
{
return ts...[0](values...[0] + values...[sizeof...(values) - 1]);
}
static_assert(first_plus_last(1, 2, 11) == 12);2.3 static_assert扩展
static_assert 的第二个消息参数支持任意常量表达式,可以直接用 std::format 等,而不是简单字符串字面量。
struct a { char c; };
static_assert(
sizeof(a) == 1,
std::format("unexpected sizeof: expected 1, got {}", sizeof(a))
);2.4 <linalg>头文件
提供类似 blas 的线性代数接口(如 std::linalg::matrix_product)。
#include <linalg> //新增头文件
#include <mdspan>
#include <array>
int main() {
std::array<double, 9> a_data = {1,2,3, 4,5,6, 7,8,9};
std::array<double, 9> b_data = {9,8,7, 6,5,4, 3,2,1};
std::array<double, 9> c_data{};
auto a = std::mdspan(a_data.data(), 3, 3);
auto b = std::mdspan(b_data.data(), 3, 3);
auto c = std::mdspan(c_data.data(), 3, 3);
std::linalg::matrix_product(a, b, c); // c = a * b
}写在最后:c++26还有很多其他小的特性,如 constexpr增强,大家感兴趣可以继续做一些深入学习。
到此这篇关于详解c++26 新特性的文章就介绍到这了,更多相关c++26 新特性内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论