如何在C ++中实现一个生成器?

如何在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++?

在C ++中我们有'iterators'。一个明确要求一个interator,显式增加和解引用它。

In C++ we have 'iterators'. One explicitly asks for an interator, explicitly increments it and dereferences it.

如果你想要它们与标准库函数一起使用,他们应该主要从 std :: forward_iterator ,并实现一些函数。

If you want them to be used with the standard library functions, they should mostly be derived from std::forward_iterator, and implement a number of it's functions.

另一种方法来模拟一个集合允许一个函数作为一个成员函数的参数,将该函数的所有值馈送(产生)给该函数:

An other way to mimic kindof a generator on a collection is allowing a function as argument to a member function that feeds (yields) all of it's values to that function:

struct MyCollection {
    int values[30];

    template< typename F >  
    void generate( F& yield_function ) const {
       int* end = values+30; // make this better in your own code :)
       for( auto i: values ) yield_function( *i );
    }
};

// usage:
c.generate([](int i){ std::cout << i << std::endl; });

// or pre-C++11:
struct MyFunction { 
    void operator() (int i)const { printf( "%d\n", i); }
};
MyCollection c;
c.generate( MyFunction() );