cpp / expert
Snippet
Infinite Stream Processing with Coroutines
C++20 coroutines provide a powerful way to implement lazy evaluation. A generator can yield values one at a time, suspending its execution until the next value is requested, which is ideal for processing infinite sequences without consuming memory for all elements.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <coroutine>#include <iostream>struct Generator {struct promise_type {int current_value;auto get_return_object() { return Generator{std::coroutine_handle<promise_type>::from_promise(*this)}; }auto initial_suspend() { return std::suspend_always{}; }auto final_suspend() noexcept { return std::suspend_always{}; }auto yield_value(int value) { current_value = value; return std::suspend_always{}; }void unhandled_exception() { std::terminate(); }void return_void() {}};std::coroutine_handle<promise_type> handle;};
Breakdown
1
struct promise_type
The internal state machine controller required for C++20 coroutines.
2
yield_value(int value)
Captures the value and suspends the function, returning control to the caller.
3
std::suspend_always{}
A standard awaitable that always pauses execution at the specified point.