# std::expected<T,E>::or_else

From cppreference.com
< cpp‎ | utility‎ | expected

template< class F > constexpr auto or_else( F&& f ) &; | (1) | (since C++23)
template< class F > constexpr auto or_else( F&& f ) const&; | (2) | (since C++23)
template< class F > constexpr auto or_else( F&& f ) &&; | (3) | (since C++23)
template< class F > constexpr auto or_else( F&& f ) const&&; | (4) | (since C++23)

If *this contains an error value, invokes f and returns its result; otherwise, returns a `std::expected` object that contains a copy of `value()`. The contained value (`error()`) is passed as an argument to f.

Let `G` be:

- for overloads (1-2), std::remove_cvref_t<std::invoke_result_t<F, decltype(error())>>;
- for overloads (3-4), std::remove_cvref_t<std::invoke_result_t<F, decltype(std::move(error()))>>.

The return type is `G`, which must be a specialization of `std::expected`, and std::is_same_v<G::value_type, T> must be true.

1-2) Equivalent to

    if (has_value())
    {
        if constexpr (std::is_void_v<T>)
            return G();
        else
            return G(std::in_place, value());
    }
    else
    {
        return std::invoke(std::forward<F>(f), error());
    }

These overloads participate in overload resolution only if std::is_void_v<T> or std::is_constructible_v<T, decltype(value())> is true.
3-4) Equivalent to

    if (has_value())
    {
        if constexpr (std::is_void_v<T>)
            return G();
        else
            return G(std::in_place, std::move(value()));
    }
    else
    {
        return std::invoke(std::forward<F>(f), std::move(error()));
    }

These overloads participate in overload resolution only if std::is_void_v<T> or std::is_constructible_v<T, decltype(std::move(value()))> is true.

### Parameters

f | - | a suitable function or Callable object that returns a std::expected

### Return value

The result of f, or a std::expected object that contains a copy of the expected value, as described above.

### Notes

Feature-test macro | Value | Std | Comment
--- | --- | --- | ---
`__cpp_lib_expected` | 202211L | (C++23) | Monadic functions for `std::expected`

### Example

| This section is incomplete Reason: no example

### See also

transform_error (C++23) | returns the `expected` itself if it contains an expected value; otherwise, returns an `expected` containing the transformed unexpected value (public member function)

Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/utility/expected/or_else&oldid=155019"