On this page
  1. std::expected
  2. Overview
  3. Notes & Pitfalls
  4. Example

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

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