std::expected(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸŽ€ NAME πŸŽ€

std::expected β€” std::expected, literally the main character of this page πŸ’…. Bestie, this is the std::expected(3) manpage and it’s about to eat.


🌸 Synopsis 🌸

Defined in header <expected>.

template< class T, class E >  (since C++23)
class expected;

The class template std::expected gives you a way to store either of two values. An object of std::expected at any given time either holds an expected value of type T, or an unexpected value of type E. std::expected is never valueless β€” no cap, it always has something in it ✨.

The stored value is allocated directly within the storage occupied by the expected object. No dynamic memory allocation takes place. Periodt.

A program is ill-formed if it instantiates an expected with a reference type, a function type, or a specialization of std::unexpected. In addition, T must not be std::in_place_t or std::unexpect_t. That’s the rule, bestie πŸ™ˆ.

🧚 Template parameters 🧚

  • T β€” the type of the expected value. The type must either be (possibly cv-qualified) void, or meet the Destructible requirements (in particular, array and reference types are not allowed, so don’t even try it πŸ’€).
  • E β€” the type of the unexpected value. The type must meet the Destructible requirements, and must be a valid template argument for std::unexpected (in particular, arrays, non-object types, and cv-qualified types are not allowed 🫢).

πŸ¦‹ Member types πŸ¦‹

  • value_type β€” T
  • error_type β€” E
  • unexpected_type β€” std::unexpected<E>

πŸŽ€ Member alias templates πŸŽ€

  • rebind<U> β€” expected<U, error_type>

πŸ’– Member functions πŸ’–

  • constructor β€” constructs the expected object (public member function)
  • destructor β€” destroys the expected object, along with its contained value (public member function)
  • operator= β€” assigns contents (public member function)

πŸ‘€ Observers πŸ‘€

  • operator->, operator* β€” accesses the expected value (public member function)
  • operator bool β€” checks whether the object contains an expected value (public member function)
  • has_value β€” checks whether the object contains an expected value (public member function)
  • value β€” returns the expected value (public member function)
  • error β€” returns the unexpected value (public member function)
  • value_or β€” returns the expected value if present, another value otherwise (public member function)

🌈 Monadic operations 🌈

  • and_then β€” returns the result of the given function on the expected value if it exists; otherwise, returns the expected itself (public member function)
  • transform β€” returns an expected containing the transformed expected value if it exists; otherwise, returns the expected itself (public member function)
  • or_else β€” returns the expected itself if it contains an expected value; otherwise, returns the result of the given function on the unexpected value (public member function)
  • transform_error β€” returns the expected itself if it contains an expected value; otherwise, returns an expected containing the transformed unexpected value (public member function)

πŸ’… Modifiers πŸ’…

  • emplace β€” constructs the expected value in-place (public member function)
  • swap β€” exchanges the contents (public member function)

πŸ”₯ Non-member functions πŸ”₯

  • operator== β€” compares expected objects (C++23) (function template)
  • swap(std::expected) β€” specializes the std::swap algorithm (C++23) (function)

🧚 Helper classes 🧚

  • unexpected β€” represented as an unexpected value (C++23) (class template)
  • bad_expected_access β€” exception indicating checked access to an expected that contains an unexpected value (C++23) (class template)
  • unexpect β€” in-place construction tag for unexpected value in expected
  • unexpect_t β€” (tag) (C++23)

πŸ“ Notes πŸ“

Types with the same functionality are called Result in Rust and Either in Haskell. Cute crossover lore, honestly 🫢.

πŸ§ͺ Feature-test macro

  • __cpp_lib_expected β€” 202202L (C++23): class template std::expected and associated helper classes
  • __cpp_lib_expected β€” 202211L (C++23): Monadic functions for std::expected

✨ Example ✨

// Run this code

#include <cmath>
#include <expected>
#include <iomanip>
#include <iostream>
#include <string_view>

enum class parse_error
{
    invalid_input,
    overflow
};

auto parse_number(std::string_view& str) -> std::expected<double,
       parse_error>
{
    const char* begin = str.data();
    char* end;
    double retval = std::strtod(begin, &end);

    if (begin == end)
        return std::unexpected(parse_error::invalid_input);
    else if (std::isinf(retval))
        return std::unexpected(parse_error::overflow);

    str.remove_prefix(end - begin);
    return retval;
}

int main()
{
    auto process = [](std::string_view str)
    {
        std::cout << "str: " << std::quoted(str) << ", ";
        if (const auto num = parse_number(str); num.has_value())
            std::cout << "value: " << *num << '\n';
            // If num did not have a value, dereferencing num
            // would cause an undefined behavior, and
            // num.value() would throw std::bad_expected_access.
            // num.value_or(123) uses specified default value 123.
        else if (num.error() == parse_error::invalid_input)
            std::cout << "error: invalid input\n";
        else if (num.error() == parse_error::overflow)
            std::cout << "error: overflow\n";
        else
            std::cout << "unexpected!\n"; // or invoke std::unreachable();
    };

    for (auto src : {"42", "42abc", "meow", "inf"})
        process(src);
}

πŸ“€ Output

str: "42", value: 42
str: "42abc", value: 42
str: "meow", error: invalid input
str: "inf", error: overflow

πŸ“š References πŸ“š

  • C++23 standard (ISO/IEC 14882:2023):
    • 22.8 Expected objects [expected]

🌟 See also 🌟

  • variant β€” a type-safe discriminated union (C++17) (class template)
  • optional β€” a wrapper that may or may not hold an object (C++17) (class template)

That’s the wrap, bestie 🫢 β€” this page came from http://cppreference.com, dated 2024.06.10, and it’s the std::expected(3) manpage. Mwah πŸ’‹.
πŸ“¦ where this page comes from