1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| #include <coroutine> #include <functional> #include <iostream>
void thirdFunc(int i, const std::function<void(int j)>& callback) { callback(i + 1); }
auto thirdFunc2Co(int i) { struct awaiter : std::suspend_always { explicit awaiter(int i): i_(i), j_(0) {} void await_suspend(std::coroutine_handle<> handle) { thirdFunc(i_, [this, handle](int j) { j_ = j; handle(); }); } int await_resume() { return j_; } int i_, j_; }; return awaiter(i); }
struct ReturnObject { struct promise_type { ReturnObject get_return_object() { return { .h_ = std::coroutine_handle<promise_type>::from_promise(*this) }; } std::suspend_never initial_suspend() { return {}; } std::suspend_always yield_value(unsigned int value) { value_ = value; return {}; } void return_value(unsigned int value) { value_ = value; } std::suspend_always final_suspend() noexcept { return {}; } void unhandled_exception() {} unsigned int value_; }; std::coroutine_handle<promise_type> h_; };
ReturnObject counter() { int j = co_await thirdFunc2Co(1); co_return j; }
int main() { auto h = counter().h_; auto& promise = h.promise(); std::cout << promise.value_ << std::endl; h.destroy(); return 0; }
|