#include <iostream>
#include <coroutine>
struct generator {
struct promise_type {
int current_value;
std::suspend_always yield_value(int value) {
current_value = value;
return {};
}
std::suspend_always initial_suspend() { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
generator get_return_object() { return generator{this}; }
void return_void() {}
void unhandled_exception() {}
};
generator(promise_type* p)
: coroutine_handle{std::coroutine_handle<promise_type>::from_promise(*p)} {}
~generator() { coroutine_handle.destroy(); }
std::coroutine_handle<promise_type> coroutine_handle; // 协程句柄,用于管理暂停或执行的协程以及Promise对象
int next() {
coroutine_handle.resume();
return coroutine_handle.promise().current_value;
}
};
generator fib(int n) {
int a = 0, b = 1;
while (n--) {
co_yield b;
auto t = a;
a = b;
b += t;
}
}
int main() {
auto gen = fib(10);
for (int i = 0; i < 10; i++) {
std::cout << gen.next() << '\n';
}
}
标签:handle,generator,coroutine,int,C++,return,value,协程
From: https://www.cnblogs.com/codingbigdog/p/17204811.html