Skip to content

std::expected (C++23)

In a nutshell

Either holds an expected value T or an unexpected error E—a type-safe, zero-overhead error propagation mechanism that replaces exceptions and the error_code pattern.

cpp
#include <expected>

Core API Cheat Sheet

OperationSignatureDescription
Construct (success)expected(T)Wraps a normal value
Construct (error)expected(unexpected<E>)Wraps an error (std::unexpected)
Check successhas_value()Whether it holds a normal value
Implicit bool conversionoperator bool()Same as has_value
Get valuevalue()Gets reference to normal value (throws exception on failure)
Get errorerror()Gets reference to the error
Dereferenceoperator*()Gets normal value (unchecked, undefined behavior if error)
Chain transformtransform(f)If has value, applies f to value and wraps result
Chain error handlingand_then(f)If has value, calls f and returns its expected result
Error branchor_else(f)If has error, calls f to handle error
Error transformtransform_error(f)If has error, applies f to error
Create success valuemake_expected(T)Factory: directly constructs success
Create error valuemake_unexpected(E)Factory: constructs unexpected for implicit conversion to expected

Minimal Example

cpp
#include <expected>
#include <iostream>
#include <string>

std::expected<int, std::string> parse_int(std::string_view str) {
    if (str.empty()) return std::unexpected("Empty string");
    // ... parsing logic ...
    return 42; // Success
}

int main() {
    auto result = parse_int("123");
    if (result) {
        std::cout << "Value: " << result.value() << "\n";
    } else {
        std::cerr << "Error: " << result.error() << "\n";
    }
    return 0;
}

Embedded Applicability: High

  • Zero-overhead abstraction: size equals max(sizeof(T), sizeof(E)) plus a discriminator flag, no heap allocation.
  • Replaces exception handling mechanisms, suitable for embedded environments with exceptions disabled (-fno-exceptions).
  • More type-safe than the error_code + output parameter pattern, forcing the caller to handle errors.
  • Chaining operations (transform/and_then) allows composing complex workflows while keeping code linear and readable.

Compiler Support

GCCClangMSVC
121619.36

See Also


部分内容参考自 cppreference.com,采用 CC-BY-SA 4.0 许可

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05