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

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

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

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

If `T` is not (possibly cv-qualified) void, the contained value (`value()`) is passed as an argument to f; otherwise f takes no argument.

Let `U` be:

- if `T` is not (possibly cv-qualified) void:
  - for overloads (1-2), std::remove_cvref_t<std::invoke_result_t<F, decltype(value())>>;
  - for overloads (3-4), std::remove_cvref_t<std::invoke_result_t<F, decltype(std::move(value()))>>;
- otherwise (T is possibly cv-qualified void), std::remove_cvref_t<std::invoke_result_t<F>>.

The return type is `U`, which must be a specialization of `std::expected`, and std::is_same_v<U::error_type, E> must be true.

1-2) Equivalent to

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

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

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

These overloads participate in overload resolution only if std::is_constructible_v<E, decltype(std::move(error()))> 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 an error 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

unexpect_t unexpect (C++23) | in-place construction tag for unexpected value in `expected` (class) (constant)
transform (C++23) | returns an `expected` containing the transformed expected value if it exists; otherwise, returns the `expected` itself (public member function)

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