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/