std::unexpected
什么是 std::unexpected
std::unexpected<E> 是 C++23 引入的辅助类模板,定义在 <expected> 头文件中。它用来包装错误值,使其可以被隐式转换为 std::expected<T, E> 的错误状态。当一个函数返回 std::unexpected(error) 时,表示这个函数的执行失败了。
#include <expected>
std::expected<int, std::string> divide(int a, int b) {
if (b == 0)
return std::unexpected("除数不能为零"); // 返回错误
return a / b; // 返回成功值
}std::unexpected 是 std::expected 错误处理体系中不可分割的一部分——它负责构造错误状态,就像成功值可以直接 return 一样。
基本示例
#include <iostream>
#include <expected>
#include <string>
#include <vector>
// ============================
// 示例1:基本构造和使用
// ============================
void basic_demo() {
// 直接构造 unexpected
std::unexpected err1(42); // 包装 int 错误
std::unexpected err2(std::string("失败")); // 包装 string 错误
// 访问错误值
std::cout << "错误1: " << err1.error() << std::endl; // 42
std::cout << "错误2: " << err2.error() << std::endl; // 失败
// CTAD(类模板参数推导)
std::unexpected err3("hello"); // 推导为 unexpected<const char*>
}
// ============================
// 示例2:在函数中返回 unexpected
// ============================
enum class MathError {
DivisionByZero,
Overflow,
Underflow
};
std::expected<double, MathError> safe_divide(double a, double b) {
if (b == 0.0) {
return std::unexpected(MathError::DivisionByZero);
}
double result = a / b;
if (result > 1e308) {
return std::unexpected(MathError::Overflow);
}
return result; // 隐式转换为 expected 的成功状态
}
void function_demo() {
auto r1 = safe_divide(10.0, 3.0);
auto r2 = safe_divide(10.0, 0.0);
if (r1) std::cout << "10/3 = " << *r1 << std::endl;
if (!r2) {
std::cout << "10/0 错误: ";
switch (r2.error()) {
case MathError::DivisionByZero: std::cout << "除零"; break;
case MathError::Overflow: std::cout << "溢出"; break;
case MathError::Underflow: std::cout << "下溢"; break;
}
std::cout << std::endl;
}
}
// ============================
// 示例3:就地构造(in_place)
// ============================
struct DetailedError {
int code;
std::string message;
std::string source;
DetailedError(int c, std::string msg, std::string src)
: code(c), message(std::move(msg)), source(std::move(src)) {}
};
std::expected<int, DetailedError> complex_operation() {
// 用 std::in_place 就地构造复杂的错误对象
return std::unexpected(std::in_place, 404, "资源未找到", "database");
}
void in_place_demo() {
auto result = complex_operation();
if (!result) {
const auto& err = result.error();
std::cout << "错误码: " << err.code
<< ", 消息: " << err.message
<< ", 来源: " << err.source << std::endl;
}
}
// ============================
// 示例4:unexpected 的比较
// ============================
void comparison_demo() {
std::unexpected e1(42);
std::unexpected e2(42);
std::unexpected e3(99);
// unexpected 支持 == 比较(比较内部的错误值)
std::cout << std::boolalpha;
std::cout << "e1 == e2: " << (e1 == e2) << std::endl; // true
std::cout << "e1 == e3: " << (e1 == e3) << std::endl; // false
}
// ============================
// 示例5:unexpected 与 expected 的交互
// ============================
void interaction_demo() {
// unexpected 可以赋值给 expected
std::expected<int, std::string> result = std::unexpected("出错了");
std::cout << "has_value: " << std::boolalpha << result.has_value() << std::endl;
std::cout << "error: " << result.error() << std::endl;
// 也可以用 unexpected 构造 expected
std::expected<std::string, int> r2{std::unexpected(404)};
std::cout << "错误码: " << r2.error() << std::endl;
// expected 之间的比较也可以用 unexpected
std::expected<int, int> r3 = std::unexpected(42);
std::cout << "r3 == unexpected(42): " << (r3 == std::unexpected(42)) << std::endl; // true
}
// ============================
// 示例6:多种错误类型的统一处理
// ============================
struct AppError {
enum class Kind { Network, Parse, Auth, Unknown };
Kind kind;
std::string detail;
};
std::expected<std::string, AppError> fetch_data() {
return std::unexpected(AppError{
AppError::Kind::Network,
"连接超时"
});
}
std::expected<int, AppError> parse_data(const std::string& data) {
return std::unexpected(AppError{
AppError::Kind::Parse,
"无效的 JSON 格式"
});
}
void app_error_demo() {
auto data = fetch_data();
if (!data) {
const auto& err = data.error();
std::cout << "错误类型: ";
switch (err.kind) {
case AppError::Kind::Network: std::cout << "网络"; break;
case AppError::Kind::Parse: std::cout << "解析"; break;
case AppError::Kind::Auth: std::cout << "认证"; break;
default: std::cout << "未知"; break;
}
std::cout << ", 详情: " << err.detail << std::endl;
}
}
int main() {
std::cout << "=== 基本构造 ===" << std::endl;
basic_demo();
std::cout << "\n=== 函数返回 ===" << std::endl;
function_demo();
std::cout << "\n=== 就地构造 ===" << std::endl;
in_place_demo();
std::cout << "\n=== 比较 ===" << std::endl;
comparison_demo();
std::cout << "\n=== 交互 ===" << std::endl;
interaction_demo();
std::cout << "\n=== 应用错误 ===" << std::endl;
app_error_demo();
return 0;
}unexpected 的成员函数
| 函数 | 说明 |
|---|---|
unexpected(val) | 构造,包装错误值 |
unexpected(std::in_place, args...) | 就地构造错误值 |
error() | 获取错误值的引用(const 和非 const 版本) |
operator== | 比较两个 unexpected 的错误值 |
swap() | 交换两个 unexpected |
unexpected 和 unexpect_t
标准还定义了一个标签类型 std::unexpect_t 和对应的常量 std::unexpect,用于在 expected 的构造函数中直接就地构造错误值:
// 用 unexpect 标签在 expected 构造函数中就地构造错误
std::expected<int, std::string> result(std::unexpect, "错误消息");适用场景
- 在返回
std::expected的函数中表示失败 - 包装枚举、字符串或自定义结构体作为错误值
- 就地构造复杂错误对象(避免额外拷贝)
- 与 expected 的比较操作配合使用
常见问题
为什么需要 unexpected,不能直接返回错误值吗?
因为 std::expected<T, E> 的成功值和错误值可能是相同类型。比如 expected<int, int>,直接返回 42 是成功还是失败?unexpected 消除了这种歧义——return 42 是成功,return unexpected(42) 是失败。
unexpected 可以包装 void 吗?
不可以。std::unexpected<void> 是不允许的,因为错误值需要携带信息。
unexpected 支持移动语义吗?
支持。unexpected 的错误值可以通过移动语义传递,避免不必要的拷贝。
注意事项
- unexpected 必须和 expected 搭配使用
- E 不能是 void、引用类型、数组类型或函数类型
- unexpected 支持 CTAD——
std::unexpected("error")推导为unexpected<const char*> - 就地构造用
std::in_place标签避免临时对象 - unexpected 的 error() 返回引用,可以修改
总结
std::unexpected 是 std::expected 错误处理体系的关键组件,负责将错误值包装为可以被 expected 识别的错误状态。在返回 expected 的函数中,成功值直接 return,错误值通过 return std::unexpected(err) 返回。unexpected 支持 CTAD、就地构造、比较操作和移动语义。配合 std::unexpect 标签,可以在 expected 的构造函数中直接就地构造错误值。