On this page
std::expected
Prev: std::variant | Up: containers | Next: algorithm_and_ranges
Rel: std::optional, std::variant
Ref: cppreference — std::expected
Tags: #public #prog #cpp #stdlib #containers #tier/standard
Overview
std::expected<T, E> (<expected>, C++23) is a vocabulary type holding either an expected value T or an error E (std::unexpected(err)), analogous to Rust's Result<T, E>. It enables explicit, zero-exception error propagation for recoverable failures.
Notes & Pitfalls
- C++23 Result type (
std::expected<T, E>): Carries either a valueTor an errorstd::unexpected(e)with monadic.and_then()/.transform()/.or_else()—no exception overhead.
Example
#include <cassert>
#include <expected>
#include <string>
std::expected<int, std::string> divide(int a, int b) {
if (b == 0) return std::unexpected("division by zero");
return a / b;
}
int main() {
assert(divide(10, 2).value() == 5);
assert(!divide(10, 0).has_value());
}
Linked from
Related notes
- tuts/cpp/stdlib/containers/optional Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/variant Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib
- tuts/cpp/stdlib/algorithm_and_ranges Linked here; shared tags: #cpp, #prog, #stdlib
- tuts/cpp/stdlib/containers/array shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/map shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/span shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/string shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/string_view shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/unordered_map shared tags: #containers, #cpp, #prog, #stdlib, #tier