Generator< T > Class Template Reference

#include <Pt/Generator.h>

Represents a coroutine that yields a sequence of values and may itself co_await. More...

Inherits AwaiterBase.

Classes

class  NextAwaiter
 Provides the awaitable returned by Generator::next(). More...

Public Member Functions

 Generator (handle_type h)
 Constructs a generator that takes ownership of h.
 Generator (Generator &&other) noexcept
 Moves the coroutine frame from other.
 ~Generator ()
 Cancels the generator if it still owns a coroutine frame.
void cancel () override
 Cancels the generator.
NextAwaiter next ()
 Returns an awaitable that produces the next value.
value ()
 Returns the last yielded value.

Detailed Description

template<typename T>
class Pt::Generator< T >

A Generator produces values lazily with co_yield. Unlike a synchronous generator, its body may also co_await.

Consume a generator from a Task. Await Generator::next() until it returns false and read each value with Generator::value().

A Generator is move-only and owns the coroutine frame. Generator<T&> yields a reference. That object must remain valid until the next Generator::next() or until the generator is destroyed.

Only one Generator::next() may be pending. Awaiting next() while another next() is already pending throws std::logic_error.

Exceptions that leave the coroutine body are rethrown from the Generator::next() await.

The following task sums the values of a generator:

Pt::Generator<int> squares(int n)
{
for(int i = 1; i <= n; ++i)
co_yield i * i;
}
Pt::Task<int> sumSquares(int n)
{
auto gen = squares(n);
int sum = 0;
while( co_await gen.next() )
sum += gen.value();
co_return sum;
}
Represents a coroutine that yields a sequence of values and may itself co_await.
Definition Generator.h:163
Represents a cancellable C++20 coroutine that produces a single result.
Definition Coroutine.h:436

Member Function Documentation

◆ cancel()

template<typename T>
void cancel ( )
overridevirtual

Aborts the pending awaitable, if any, detaches an in-flight next() await, and destroys the coroutine frame.

Implements AwaiterBase.

◆ next()

template<typename T>
NextAwaiter next ( )

co_await of the result is true while a value is available. Use Generator::value() to read that value.

◆ value()

template<typename T>
T value ( )

Valid after a co_await of Generator::next() returned true.