Header Reference: <expected>

Header Reference: <expected>

The value-or-error result type std::expected and the main patterns it supports in modern C++ APIs.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

What header pages are for

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.

  • Start here when you already know roughly which header you need but want a fast operational summary.
  • Use the example section below as a minimal pattern, then adapt it to your real container, ownership, text, or concurrency workflow.
  • Jump to broader index pages when you need exhaustive coverage rather than a header-focused summary.

Header Reference: <expected>

Main types

What it provides

When to use it

When not to use it

Small worked example

#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.

Selection guide

Nearby pages

Minimal example

#include <expected>
#include <string>

std::expected<int, std::string> parse(bool ok) {
    if (!ok) {
        return std::unexpected("parse failure");
    }
    return 42;
}

What to verify before relying on this header

  • Whether the type models ownership, borrowing, type erasure, value transport, or a compile-time constraint.
  • Which operations are constant time versus potentially allocating, dispatching, or instantiating more template machinery than expected.
  • How the facility composes with nearby headers like ``, ``, ``, or ``.