Namespaces
Variants

std::execution::as_awaitable

From cppreference.com
 
 
Execution control library
Concepts
 
Defined in header <execution>
struct as_awaitable_t { /* unspecified */ };
(1) (since C++26)
inline constexpr as_awaitable_t as_awaitable{};
(2) (since C++26)
(customization point object)
Call signature
template< class Expr, class Promise >
/*awaitable*/ as_awaitable( Expr&& expr, Promise& p );
(3) (since C++26)

Makes expr awaitable in a coroutine whose promise object is p, so that it can be the operand of co_await there. If the type of expr models sender, and the sender has at most one value completion signature in the environment of p (see Awaiting a sender), the result is an awaitable that connects and starts the sender, suspends the coroutine until the sender completes, and turns its completion into the result of the co_await expression, an exception, or a coroutine that is never resumed. If expr is already awaitable in the coroutine, it is returned as it is. A type can also provide its own awaitable with a member function as_awaitable. For any other expr, the co_await expression is ill-formed.

as_awaitable is meant to be called from the await_transform member function of a promise type, which then lets the coroutine co_await senders. The promise type of task does this, and with_awaitable_senders is a base class that gives a promise type of a program such an await_transform. A program that uses these coroutine types does not need to call as_awaitable itself.

1) The type of the customization point object.
3) Returns, in this order of preference:
  • expr.as_awaitable(p) if that expression is valid. A type can provide its own awaitable this way, and a sender type of the standard library may do so as well, with the behavior described below. The program is ill-formed if the result cannot be awaited in the coroutine.
  • Otherwise, if decltype((expr)) models execution::sender_in<execution::env_of_t<Promise>> and the sender has at most one value completion signature, it is first prepared for awaiting as described below; if the resulting sender has a member function as_awaitable, the result of calling it with p.
  • Otherwise, expr itself if it is already awaitable in the coroutine. An awaitable that is also a sender is therefore awaited directly, not through its sender interface.
  • Otherwise, if decltype((expr)) models execution::sender_in<execution::env_of_t<Promise>> and the sender has at most one value completion signature, an awaitable that awaits that sender, described below.
  • Otherwise, expr itself. It is not awaitable in the coroutine, so the co_await expression is ill-formed.
The call is ill-formed if p is not an lvalue. expr and p are evaluated in an unspecified order, and p is evaluated only once.

Awaiting a sender

A sender can be awaited if, in the environment execution::get_env(p) of the promise, it has at most one value completion signature. The co_await expression then has the type

  • void if the sender completes with execution::set_value(), without arguments, or if it never completes with a value;
  • std::decay_t<T> if it completes with execution::set_value(t), where t has type T;
  • std::tuple<std::decay_t<Ts>...> if it completes with several values of types Ts....

A sender that can complete with values of different types, such as one with both set_value_t() and set_value_t(int) completion signatures, cannot be awaited directly. into_variant combines its value completions into one std::variant.

Before the sender is awaited, it is transformed by transform_sender. Then, if the attributes object of the sender has a get_await_completion_adaptor query, the sender adaptor it returns is applied. The author of a sender uses this to provide a result that is easier to use in a coroutine than its completions: for example, a sender that completes with either set_value_t() or set_value_t(T) can provide an adaptor that combines them into a single std::optional<T>.

The awaitable connects the sender to a receiver when it is created, and starts the resulting operation when the coroutine suspends. When the operation completes:

  • with execution::set_value(rcvr, vs...), the values are stored in the awaitable and the coroutine is resumed; the co_await expression gives the stored result as described above. If storing the values throws an exception, the co_await expression throws it instead;
  • with execution::set_error(rcvr, err), the coroutine is resumed and the co_await expression throws an exception: err itself if it is an std::exception_ptr, std::system_error(err) if it is an std::error_code, and a copy of err otherwise;
  • with execution::set_stopped(rcvr), the coroutine is not resumed. The awaitable calls p.unhandled_stopped() and resumes the coroutine handle that it returns instead.

The environment of the receiver gives the sender the answers to forwarding queries, such as std::get_stop_token, get_scheduler and std::get_allocator, from the environment of the promise, execution::get_env(p). Only forwarding queries are guaranteed to reach the sender: co_await execution::read_env(q) in the coroutine is not portable for a query q that is not a forwarding query, even if the environment of the promise answers it. Some implementations, such as stdexec, pass on all queries. A promise type without a get_env member function has an empty environment.

Parameters

expr - the operand of co_await, usually a sender
p - the promise object of the coroutine that evaluates the co_await expression

Return value

An object that can be awaited in the coroutine, or expr itself, as described above.

Customization point objects

The name execution::as_awaitable denotes a customization point object, which is a const function object of a literal semiregular class type. The cv-unqualified version of its type is a tag type denoted as execution::as_awaitable_t. See CustomizationPointObject for details.

Notes

  • The promise type of a coroutine that awaits a sender that can complete with set_stopped must have a member function unhandled_stopped() that returns a type convertible to std::coroutine_handle<>. A stopped completion is not an exception: the coroutine is not resumed, so catch clauses do not see it and its local variables are not destroyed until the coroutine is destroyed. unhandled_stopped usually reports the stopped completion to whatever started the coroutine, for example by completing with set_stopped itself as task does, and returns the coroutine handle that should run next, or std::noop_coroutine. To handle a stopped completion inside the coroutine, await the sender through stopped_as_optional, stopped_as_error, upon_stopped or let_stopped.
  • The awaitable resumes the coroutine from inside the completion function of the sender. If the sender completes on another thread, the rest of the coroutine runs on that thread; task uses affine to return to the scheduler it was started on. If the sender completes inside start, as just does, the coroutine is resumed in a function call nested in its own suspension, and a loop that awaits many such senders can run out of stack space. Some implementations, such as stdexec, detect a completion inside start and resume the coroutine after start returns instead.
  • The operation state of an awaited sender is stored in the awaitable, which is a temporary object in the coroutine frame. Awaiting a sender therefore does not allocate memory beyond the coroutine frame, unless the sender itself does.

Example

job is a minimal coroutine type whose promise type uses as_awaitable in its await_transform, so the coroutine can await senders.
The execution control library components may not be available in the online compilers yet, so this link runs the example on Compiler Explorer with stdexec (one of the reference implementations).

#include <coroutine>
#include <exception>
#include <execution>
#include <print>
#include <system_error>
#include <utility>

namespace ex = std::execution;

// A minimal coroutine type that starts at once and can await senders
struct job
{
    struct promise_type
    {
        job get_return_object()
        {
            return {std::coroutine_handle<promise_type>::from_promise(*this)};
        }
        std::suspend_never initial_suspend() noexcept { return {}; }
        std::suspend_always final_suspend() noexcept { return {}; }
        void return_void() {}
        void unhandled_exception() { std::terminate(); }

        // Every operand of co_await goes through as_awaitable
        template<class T>
        decltype(auto) await_transform(T&& t)
        {
            return ex::as_awaitable(std::forward<T>(t), *this);
        }

        // Called instead of resuming when a sender completes with set_stopped
        std::coroutine_handle<> unhandled_stopped() noexcept
        {
            std::println("Stopped: the coroutine is not resumed");
            return std::noop_coroutine();
        }
    };

    std::coroutine_handle<promise_type> handle;

    ~job() { handle.destroy(); }
};

job run()
{
    // A sender of one value: co_await gives the value
    int i = co_await ex::just(42);
    std::println("Value: {}", i);

    // A sender of several values: co_await gives a std::tuple
    auto [n, c] = co_await ex::just(1, 'a');
    std::println("Values: {} {}", n, c);

    // A sender of no values: co_await gives void
    co_await ex::just();

    // An error is thrown; an std::error_code is thrown as std::system_error
    try
    {
        co_await ex::just_error(std::make_error_code(std::errc::timed_out));
    }
    catch (const std::system_error& e)
    {
        if (e.code() == std::errc::timed_out)
            std::println("Caught std::system_error: timed out");
    }

    // An awaitable that is not a sender is awaited as it is
    co_await std::suspend_never{};

    co_await ex::just_stopped();
    std::println("Not printed");
}

int main()
{
    job j = run();
    std::println("Back in main");
}

Output:

Value: 42
Values: 1 a
Caught std::system_error: timed out
Stopped: the coroutine is not resumed
Back in main

See also

when used as the base class of a coroutine promise type, enables senders to be awaitable within that coroutine type
(class template) [edit]
represents a sender that can be used as the return type of coroutine functions
(class template) [edit]
asks a queryable object for its associated awaitable completion adaptor
(customization point object)[edit]
connects a sender with a receiver
(customization point object)[edit]
adapts a sender that can complete with several different sets of values into one that completes with a single std::variant of tuples
(customization point object)[edit]
returns a sender that maps the value channel to std::optional<std::decay_t<T>> and the stopped channel to std::nullopt
(customization point object)[edit]