Implementing a Simple Generator
Build a generator coroutine that lazily yields values.
Generators as Coroutines
A generator is a coroutine that yields values one at a time. Each call to the generator produces the next value and suspends.
The Generator Type
Define a class with a nested promise_type. The compiler uses it to manage the coroutine s state.
template <typename T>
struct Generator {
struct promise_type {
T current_value;
Generator get_return_object() {
return Generator{std::coroutine_handle<promise_type>::from_promise(*this)};
}
std::suspend_always initial_suspend() { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
void return_void() {}
std::suspend_always yield_value(T value) {
current_value = value;
return {};
}
void unhandled_exception() { std::terminate(); }
};
std::coroutine_handle<promise_type> h;
// ... constructors, destructor, next() ...
};All lessons in this course
- Coroutine Concepts co_await co_yield co_return
- Implementing a Simple Generator
- Async Tasks and Awaiter Types
- Coroutine Frame Allocation