在C++23标准之前,处理可能失败的操作通常要借助异常或者输出参数返回错误码,代码里充斥着大量的if判断与早返回。C++23正式纳入的std::expected让函数可以显式声明成功值与错误值,并通过成员函数完成链式调用,从而优雅地处理复杂逻辑跳转。

什么是std::expected
std::expected<T, E>是一个模板类,它要么保存类型T的值,要么保存类型E的错误。相比抛出异常,它把错误当作普通数据来处理,调用方必须主动检查,避免了隐式控制流。
#include <expected>
#include <string>
#include <iostream>
// 定义错误类型
struct ErrorInfo {
int code;
std::string msg;
};
// 可能失败的函数
std::expected<int, ErrorInfo> parse_number(const std::string& s) {
try {
return std::stoi(s);
} catch (...) {
return std::unexpected(ErrorInfo{1, "转换失败"});
}
}
链式调用处理错误
std::expected提供了and_then、transform、or_else等方法。and_then在前一步成功时继续执行,失败则跳过;or_else在失败时进行补救或记录。这样多层调用不需要每层都写判断。
#include <expected>
#include <string>
#include <iostream>
std::expected<int, ErrorInfo> step1(const std::string& s) {
if (s.empty()) return std::unexpected(ErrorInfo{2, "空字符串"});
return std::stoi(s);
}
std::expected<int, ErrorInfo> step2(int v) {
if (v < 0) return std::unexpected(ErrorInfo{3, "负数"});
return v * 2;
}
void run() {
auto result = step1("10")
.and_then(step2)
.or_else([](const ErrorInfo& e) -> std::expected<int, ErrorInfo> {
std::cout << "错误:" << e.msg << "n";
return std::unexpected(e);
});
if (result) {
std::cout << "结果:" << *result << "n";
}
}
复杂逻辑跳转示例
假设我们要读取配置、连接服务、发送数据,任意一步失败都要终止并上报。使用std::expected可以把流程写成一条直线,错误自动跳出后续步骤。
#include <expected>
#include <string>
#include <iostream>
struct Err { int id; std::string text; };
std::expected<std::string, Err> load_conf() {
return "127.0.0.1";
}
std::expected<int, Err> connect(const std::string& addr) {
if (addr != "127.0.0.1") return std::unexpected(Err{1, "地址错误"});
return 200;
}
std::expected<bool, Err> send_data(int fd) {
if (fd != 200) return std::unexpected(Err{2, "连接异常"});
return true;
}
void workflow() {
auto r = load_conf()
.and_then([](auto a) { return connect(a); })
.and_then([](int fd) { return send_data(fd); });
if (!r) {
std::cout << "失败:" << r.error().text << "n";
return;
}
std::cout << "全部成功n";
}
与异常和错误码对比
| 方式 | 控制流 | 可读性 | 性能 |
|---|---|---|---|
| 异常 | 隐式跳转 | 正常路径清晰 | 抛出时开销大 |
| 错误码 | 显式判断 | 易嵌套混乱 | 无额外开销 |
| std::expected | 显式链式 | 线性清晰 | 值拷贝开销小 |
通过std::expected,C++23让错误处理从散落的判断变为连贯的表达式,复杂逻辑跳转也更加直观可控。
std_expectedC++23链式调用修改时间:2026-07-25 18:51:24