
在C++23中,std::expected 是一种全新的类型,用于更清晰、更安全地处理可能失败的函数调用。它提供了一种比异常和错误码更现代、更直观的方式来表达“期望得到一个值,但也可能得到一个错误”的语义。
std::expected<T, E> 是一个模板类,表示要么包含一个类型为 T 的成功值(the expected value),要么包含一个类型为 E 的错误值。这与 std::optional<T> 类似,但不同的是:optional 表示“有值或无值”,而 expected 明确告诉你“为什么没有值”——因为它包含了具体的错误信息。
举个例子:
假设你写一个函数来解析整数:
立即学习“C++免费学习笔记(深入)”;
std::expected<int, std::string> parse_int(const std::string& str) {
try {
size_t pos;
int value = std::stoi(str, &pos);
if (pos != str.size()) {
return std::unexpected("Invalid: extra characters");
}
return value;
} catch (const std::invalid_argument&) {
return std::unexpected("Invalid argument");
} catch (const std::out_of_range&) {
return std::unexpected("Number out of range");
}
}
调用时可以这样处理结果:
auto result = parse_int("123abc");
if (result.has_value()) {
std::cout << "Got: " << *result << "\n";
} else {
std::cout << "Parse error: " << result.error() << "\n";
}
以往我们常用以下方式处理错误:
std::expected 解决了这些问题:
实际开发中,建议这样使用:
if (auto res = compute(); res) { ... }
还支持一些便捷操作:
// 链式处理
get_user_id()
.and_then(fetch_user_data)
.or_else([](const auto& e) {
log_error(e);
return default_user();
});
目前(截至主流编译器2024年版本),std::expected 在 GCC 13+、Clang 17+ 中已部分支持,需启用 -std=c++23 并注意标准库实现进度。MSVC 正在跟进。
若暂不可用,可使用 TL::expected 第三方库作为过渡,接口高度兼容。
基本上就这些。std::expected 让 C++ 的错误处理变得更直接、更可靠,是现代 C++ 值得掌握的重要工具。
以上就是C++23的std::expected是什么_C++中优雅处理函数返回值与错误的现代方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号