C++20协程通过co_yield、co_return和promise_type实现生成器,支持懒加载整数序列。示例中Generator结合range函数按需产出值,每次next()恢复执行至下一yield,value()获取当前值,体现协程挂起与恢复机制。

在C++20中,协程(Coroutines)被正式引入语言标准,使得我们可以实现像生成器(Generator)这样的懒计算序列。一个简单的生成器可以按需产生值,而不是一次性生成所有结果,这在处理大数据流或无限序列时非常有用。
要实现一个生成器,需要了解协程的三个核心部分:
除此之外,还需要定义一个promise_type来控制协程的行为,比如如何处理yield的值、如何获取返回对象等。
下面是一个简化但可用的整数生成器实现,支持通过co_yield逐步返回int值:
立即学习“C++免费学习笔记(深入)”;
#include <coroutine>
#include <iostream>
struct Generator {
struct promise_type {
int current_value;
std::suspend_always initial_suspend() { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
Generator get_return_object() { return Generator{
std::coroutine_handle<promise_type>::from_promise(*this)
}; }
void return_void() {}
std::suspend_always yield_value(int value) {
current_value = value;
return {};
}
void unhandled_exception() { std::terminate(); }
};
std::coroutine_handle<promise_type> handle;
explicit Generator(std::coroutine_handle<promise_type> h) : handle(h) {}
~Generator() {
if (handle) handle.destroy();
}
// 禁止拷贝
Generator(const Generator&) = delete;
Generator& operator=(const Generator&) = delete;
// 支持移动
Generator(Generator&& other) noexcept : handle(other.handle) {
other.handle = nullptr;
}
Generator& operator=(Generator&& other) noexcept {
if (this != &other) {
if (handle) handle.destroy();
handle = other.handle;
other.handle = nullptr;
}
return *this;
}
bool next() {
if (!handle || handle.done()) return false;
handle.resume();
return !handle.done();
}
int value() const {
return handle.promise().current_value;
}
};
现在可以写一个函数,利用co_yield逐步返回数值:
Generator range(int start, int stop, int step = 1) {
for (int i = start; i < stop; i += step) {
co_yield i;
}
}
然后在main函数中遍历这个生成器:
int main() {
auto gen = range(1, 6);
while (gen.next()) {
std::cout << gen.value() << " ";
}
// 输出: 1 2 3 4 5
return 0;
}
每次调用next()都会恢复协程执行到下一个co_yield,value()获取当前产出的值。
基本上就这些。这个生成器虽然简单,但展示了C++20协程的核心机制。实际项目中可进一步扩展支持更多类型、异常安全、迭代器接口等。
以上就是c++++怎么实现一个简单的协程生成器(Generator)_C++协程基础与生成器实现的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号