Task< T > Class Template Reference

#include <Pt/Coroutine.h>

Represents a cancellable C++20 coroutine that produces a single result. More...

Inherits AwaiterBase.

Public Member Functions

 Task () noexcept
 Constructs an empty task with no coroutine frame.
 
 Task (handle_type h)
 Constructs a task that takes ownership of h.
 
 Task (Task &&other) noexcept
 Moves the coroutine frame from other.
 
Taskoperator= (Task &&other) noexcept
 Moves the coroutine frame from other. More...
 
 ~Task ()
 Cancels the task if it still owns a coroutine frame.
 
void run ()
 Starts execution of the coroutine. More...
 
void cancel () override
 Cancels the running coroutine. More...
 
bool done () const
 Returns true if the coroutine has finished.
 
 operator bool () const
 Returns true if the task has an associated coroutine frame.
 
result ()
 Returns the coroutine result. More...
 
bool await_ready () const noexcept
 Returns true if the inner coroutine has already finished.
 
template<typename P >
std::coroutine_handle await_suspend (std::coroutine_handle< P > outer)
 Suspends the outer coroutine and starts the inner coroutine. More...
 
await_resume ()
 Returns the result of the inner task. More...
 

Detailed Description

template<typename T = void>
class Pt::Task< T >

A Task is move-only and owns the coroutine frame. A default-constructed task is empty; Task::operator bool() is false until a coroutine is assigned. Move assignment cancels the current task first.

Task<void> produces no value. Task<T&> returns a reference; that object must outlive the consumer.

An outer coroutine can co_await an inner Task. The co_await expression is the inner result:

{
co_return 41;
}
{
int n = co_await inner();
co_return n + 1;
}

Task::run() and awaiting a task that is already pending throw std::logic_error.

Member Function Documentation

◆ operator=()

Task& operator= ( Task< T > &&  other)
noexcept

Cancels this task before taking ownership of other.

◆ run()

void run ( )

Has no effect if the task is empty or already finished.

Exceptions
%std::logic_errorif the task is already pending.

◆ cancel()

void cancel ( )
overridevirtual

Aborts the pending awaitable, if any, and destroys the coroutine frame. The task is empty afterwards.

Implements AwaiterBase.

◆ result()

T result ( )

Use this after Task::done() is true. If the coroutine body exited with an exception, that exception is rethrown.

◆ await_suspend()

std::coroutine_handle await_suspend ( std::coroutine_handle< P >  outer)
Exceptions
%std::logic_errorif the task is already pending.

◆ await_resume()

T await_resume ( )

Rethrows if the inner coroutine body exited with an exception.

Represents a cancellable C++20 coroutine that produces a single result.
Definition: Coroutine.h:436