Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::expected: a value or an explicit error

std::expected<T, E> holds exactly one of two states: an expected T value or an E error object, with no empty state.

Version: C++23

Syntax

template<class T, class E>
class expected {
public:
    constexpr explicit operator bool() const noexcept;
    constexpr T* operator->() noexcept;
    constexpr T& operator*() & noexcept;
    constexpr T& value() &;
    constexpr E& error() & noexcept;
    template<class U> constexpr T value_or(U&& fallback) const &;
};

std::expected<T, E> from <expected> is a C++23 discriminated union. Construct success from a T value or std::in_place, and failure with std::unexpected(error) or std::unexpect; has_value() and explicit conversion to bool distinguish the states.

value() returns the stored value and, in the error state, throws std::bad_expected_access<E> containing the error. error() does not throw but may be called only when has_value() is false; likewise operator* and operator-> require the value state. The example safely prints 7 for success and missing for failure.

std::expected::operator bool returns the success state just like has_value(). std::expected::operator* and std::expected::operator-> provide unchecked value access and require the success state; violating that precondition has undefined behavior. std::expected::error returns a reference to the error and conversely requires the error state; use the potentially throwing value() for checked value access.

T must be void or a complete non-array object type satisfying the standard exclusions; E must be an unqualified object type, not an array or an unexpected specialization. The object is never valueless, but copy, move, and monadic operations have their own type constraints. value_or still evaluates its fallback argument before the call like an ordinary function argument.

Examples

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

std::expected<int, std::string> fetch(bool found) {
    if (found) return 7;
    return std::unexpected(std::string{"missing"});
}

int main() {
    const auto good = fetch(true);
    const auto bad = fetch(false);
    std::cout << good.value() << ' ' << bad.error() << '\n';
}

Result

7 missing

std::expected → 7 missing

Sources