wwa-coro 0.0.1
Yet Another C++20 Coroutine Library
advance_with_begin.cpp

Shows how to (ab)use begin() to advance the iterator.

#include <iostream>
#include <utility>
#include "eager_task.h"
#include "generator.h"
#include "task.h"
namespace {
wwa::coro::task<int> get_next_value(int n)
{
co_return n + 1;
}
wwa::coro::async_generator<int> async_first_n(int n)
{
int v = 0;
while (v < n) {
co_yield v;
v = co_await get_next_value(v);
}
}
wwa::coro::generator<int> sync_first_n(int n)
{
int v = 0;
while (v < n) {
co_yield v;
++v;
}
}
wwa::coro::eager_task iterate_over_async()
{
auto gen = async_first_n(5);
auto it = co_await gen.begin();
auto end = gen.end();
do {
std::cout << *it << " ";
} while (co_await gen.begin() != end);
std::cout << "\n";
}
void iterate_over_sync()
{
auto gen = sync_first_n(5);
auto it = gen.begin();
auto end = gen.end();
do {
std::cout << *it << " ";
} while (gen.begin() != end);
std::cout << "\n";
}
void iterate_over_adapted_async()
{
auto async = async_first_n(5);
auto gen = wwa::coro::sync_generator_adapter(std::move(async));
auto it = gen.begin();
auto end = gen.end();
do {
std::cout << *it << " ";
} while (gen.begin() != end);
std::cout << "\n";
}
} // namespace
int main()
{
std::cout << "Iterating over asynchronous generator:\n";
iterate_over_async();
std::cout << "Iterating over synchronous generator:\n";
iterate_over_sync();
std::cout << "Iterating over adapted asynchronous generator:\n";
iterate_over_adapted_async();
// Expected output:
// Iterating over asynchronous generator:
// 0 1 2 3 4
// Iterating over synchronous generator:
// 0 1 2 3 4
// Iterating over adapted asynchronous generator:
// 0 1 2 3 4
return 0;
}
Asynchronous generator.
An asynchronous generator that produces values of type Result.
Eager coroutine.
Definition eager_task.h:32
An synchronous generator that produces values of type Result.
Definition generator.h:43
A coroutine task.
Definition task.h:196
Eager coroutine.
Synchronous generator.
sync_generator_adapter(async_generator< Result >) -> sync_generator_adapter< Result >
Deduction guide for sync_generator_adapter.
Adapter for converting asynchronous generators to synchronous generators.
Coroutine-based task.