如何在 C++ 中实现生成器?
我想知道如何在 C++ 中实现像 Python 这样的生成器? Python 可以使用关键字“yield”来做到这一点。 但在 C++ 中如何实现呢?
I want to know how to implement a generator , like Python, in C++?
Python can use keyword "yield" to do so.
But how to do it in C++?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
详细说明迭代器实现:这是一个示例。它可以用作循环变量,或在 std 算法中。
To elaborate on the iterator implementation: this is an example. It can be used as a loop variable, or in std algorithms.
你确实做不到,但你可以假装做到。这是一种用 C 语言伪造它的方法,你可以使用它在 C++ 中也是如此。
You can't do it, really, but you can fake it. Here's a way you can fake it in C, which you can use in C++ as well.
多次调用协程并获得不同的答案意味着您可以保留某种状态。保持状态的方式是对象。让它们看起来像函数调用的方法是运算符重载。有关一些示例,请参阅函数对象维基百科中的文章。
Calling a coroutine multiple times and getting different answers means you keep some state. The way to keep a state is objects. The way to make them look like function call is operator overloading. For some examples see the function object article in Wikipedia.
你可以使用 boost.context (抱歉,还没有在 boost 发行版上,你必须从 提升库)。
典型的示例代码如下:
you can use boost.context (sorry, not on boost distribution yet, you'll have to get it from boost vault).
A typical example code would be like this: