Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::unexpected — explicitly marking an error result

std::unexpected<E> from <expected> wraps an error value to construct std::expected<T, E> in its failure state. It distinguishes an error from a successful result even when T and E are the same type.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <expected>
std::unexpected<E> error{error_value};
std::unexpected{error_value}
std::expected<T, E>{std::unexpected<E>{error_value}}

std::unexpected<E> is a class template available since C++23 in <expected> that stores an error value. std::unexpected{error_value} deduces the type E. Creating the wrapper does not itself throw an exception, but the constructor of the stored E can throw.

std::expected<T, E> stores either a result or an error. Passing std::unexpected<E> selects the error state; in the example, return -1; would mean a successful int result, whereas return std::unexpected{-1}; means failure. This distinction also works when T and E are identical.

std::unexpected<E>::error() accesses its stored error. For std::expected<T, E>, check the state first: if (result) means success. Use *result only on success and result.error() only on failure. In C++23, calling value() on an lvalue requires E to be copy-constructible. In the error state, result.value() throws std::bad_expected_access<E> if that exception is successfully constructed. Copying or moving the error value of type E during exception construction can throw a different exception instead.

The example requires C++23 support in both the compiler and standard library. The displayed code was run unchanged in an isolated environment, and its output was checked against the stated result. The repository compiler flag does not attest production runtime support. The supplied source document is an evolving draft, not a frozen C++23 publication.

Examples

#include <expected>
#include <initializer_list>
#include <iostream>

std::expected<int, int> half(int n) {
    if (n % 2 != 0) {
        return std::unexpected{-1};
    }
    return n / 2;
}

int main() {
    for (int n : {8, 7}) {
        auto result = half(n);
        if (result) {
            std::cout << "value: " << *result << '\n';
        } else {
            std::cout << "error: " << result.error() << '\n';
        }
    }
}

Result

value: 4
error: -1

The displayed code was run unchanged in an isolated environment. Its standard output matched the stated result exactly.

Sources