c++error-handlingc++-faqc++23std-expected

What is std::expected in C++?


In one of the most respected stackoverflow answer I found an example of std::expected template class usages: What are coroutines in C++20?

At the same time I cannot find any mentioning of this class on cppreference.com. Could you please explain what it is?


Solution

  • Actually, the best way to learn about std::expected is a funny talk by the (in)famous Andrei Alexandrescu: "Expect the Expected!"

    What std::expected is, and when it's used

    Here are three complementing explanations of what an std::expected<T, E> is:

    "How is it better than just an std::variant<T,E>?"

    It behaves somewhat like std::optional<T>, giving focus to the expected, rather than the unexpected, case:

    Actually, that last mode of access behaves differently than std::optional if we got an error: What it throws is a bad_expected_access<E>, with the returned error. This behavior can be thought of as a way to switch from expected-based to exception-based error-handling.

    "Hey, I looked for it in the standard and it isn't there!"

    std::expected will be part of the upcoming C++23 standard. The proposal (P0323) has recently been accepted.

    This being said - it is quite usable already, since it requires no new language facilities: