Coroutines — functions that can suspend and resume execution.
1#include <coroutine>2#include <iostream>34// Generator coroutine5struct Generator {6 struct promise_type {7 int current_value;8 Generator get_return_object() {9 return Generator{std::coroutine_handle<promise_type>::from_promise(*this)};10 }11 std::suspend_always initial_suspend() { return {}; }12 std::suspend_always final_suspend() noexcept { return {}; }13 std::suspend_always yield_value(int value) {14 current_value = value;15 return {};16 }17 void return_void() {}18 void unhandled_exception() { std::terminate(); }19 };2021 std::coroutine_handle<promise_type> handle;22 bool next() { handle.resume(); return !handle.done(); }23 int value() { return handle.promise().current_value; }24};2526Generator count(int n) {27 for (int i = 0; i < n; i++) {28 co_yield i;29 }30}
Use cases: