Header Reference: <expected>
Header Reference: <expected>
The value-or-error result type std::expected and the main patterns it supports in modern C++ APIs.
Header Reference: <expected>
The value-or-error result type std::expected and the main patterns it supports in modern C++ APIs.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
Header reference pages are meant to answer a practical question quickly: what this header provides, when to reach for it, and which usage rules are easiest to get wrong.
<expected>std::expected<T, E>std::unexpected<E>std::bad_expected_access<E>std::optional#include <expected>
#include <string>
#include <string_view>
std::expected<int, std::string> parse_port(std::string_view text) {
if (text.empty()) {
return std::unexpected("port was empty");
}
return 8080;
}
The useful part is not the syntax. The useful part is that the caller must handle either the value or the error explicitly, which makes local branching and recovery visible in the API.
std::expected<T, E> when callers need a value on success and structured error information on failurestd::optional<T> when the only question is whether a value exists#include <expected>
#include <string>
std::expected<int, std::string> parse(bool ok) {
if (!ok) {
return std::unexpected("parse failure");
}
return 42;
}