c++ - 在 C++0x 中实现生成器

标签 c++ c++11 generator

python 关键字 yield 对我来说是一个很好的概念抽象,让我能够将算法的重要部分提炼成人类可读的形式。我们之前讨论过:

Python generators in various languages

其中针对 C++ 中仅适用于 Windows 的库给出了答案。此外,我在问题中找到了另一个使用时髦宏扩展的示例:

Generators in C++ — invalid use of nonstatic data member

我的计算机科学知识告诉我,屈服函数有 something to do with co-routines和 monad,但我不太清楚这如何适合 C++ 或 C++0x 可以完成的任务。

似乎在 C++ 中,如果不使用宏扩展或 windows only fiber(线程),yeild 将无法实现。这是真的?问题是否随着 C++0x 的附加语言特性而改变?

最佳答案

您可以将 yield python 机制映射到 C++ 迭代器。

参见 Boost Function Input Iterator和例子:

The Function Input Iterator allows for creating iterators that encapsulate a nullary function object and a state object which tracks the number of times the iterator has been incremented. A Function Input Iterator models the InputIterator concept and is useful for creating bounded input iterators.

Like the Generator Iterator, the Function Input Iterator takes a function that models the Generator concept (which is basically a nullary or 0-arity function object). Each increment of the function Function Input Iterator invokes the generator function and stores the value in the iterator. When the iterator is dereferenced the stored value is returned.

关于c++ - 在 C++0x 中实现生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8153797/

相关文章:

c++ - 如何编写适用于两个动态数组的 strcat 函数

c++ - 十六进制字符串到十六进制字符[]

c++ - Catch 语句被完全忽略

javascript - 将 invRegex.py 移植到 Javascript (Node.js)

c++ - 从 vector 改变事物

C++ 标准 :search behavior or restriction

c++ - 有没有一种安全的方法可以同时使用 C++11 智能指针和原始指针接口(interface)?

c++ - 如何使用参数包参数 typedef 函数指针类型

spring-boot - Maven Swagger swagger-codegen-plugin 只生成模型和 Controller

python - 为什么耗尽的生成器不止一次引发 StopIteration?