The following code example is taken from the book
C++20 - The Complete Guide
by Nicolai M. Josuttis,
Leanpub, 2021
The code is licensed under a
Creative Commons Attribution 4.0 International License.
// raw code
#include <coroutine>
#include <exception> // for terminate()
class [[nodiscard]] CoroGen {
public:
// initialize members for state and customization:
struct promise_type;
using CoroHdl = std::coroutine_handle<promise_type>;
private:
CoroHdl hdl; // native coroutine handle
public:
struct promise_type {
int coroValue = 0; // recent value from co_yield
auto yield_value(int val) { // reaction to co_yield
coroValue = val; // - store value locally
return std::suspend_always{}; // - suspend coroutine
}
// the usual members:
auto get_return_object() { return CoroHdl::from_promise(*this); }
auto initial_suspend() { return std::suspend_always{}; }
void return_void() { }
void unhandled_exception() { std::terminate(); }
auto final_suspend() noexcept { return std::suspend_always{}; }
};
// constructors and destructor:
CoroGen(auto h) : hdl{h} { }
~CoroGen() { if (hdl) hdl.destroy(); }
// no copying or moving:
CoroGen(const CoroGen&) = delete;
CoroGen& operator=(const CoroGen&) = delete;
// API:
// - resume the coroutine:
bool resume() const {
if (!hdl || hdl.done()) {
return false; // nothing (more) to process
}
hdl.resume(); // RESUME
return !hdl.done();
}
// - yield value from co_yield:
int getValue() const {
return hdl.promise().coroValue;
}
};