Equivalent C++ to Python generator pattern

前端 未结 12 2352
Happy的楠姐
Happy的楠姐 2020-11-28 18:42

I\'ve got some example Python code that I need to mimic in C++. I do not require any specific solution (such as co-routine based yield solutions, although they would be acce

12条回答
  •  遥遥无期
    2020-11-28 19:10

    Since Boost.Coroutine2 now supports it very well (I found it because I wanted to solve exactly the same yield problem), I am posting the C++ code that matches your original intention:

    #include 
    #include 
    #include 
    #include 
    
    typedef boost::coroutines2::coroutine> coro_t;
    
    void pair_sequence(coro_t::push_type& yield)
    {
        uint16_t i = 0;
        uint16_t j = 0;
        for (;;) {
            for (;;) {
                yield(std::make_pair(i, j));
                if (++j == 0)
                    break;
            }
            if (++i == 0)
                break;
        }
    }
    
    int main()
    {
        coro_t::pull_type seq(boost::coroutines2::fixedsize_stack(),
                              pair_sequence);
        for (auto pair : seq) {
            print_pair(pair);
        }
        //while (seq) {
        //    print_pair(seq.get());
        //    seq();
        //}
    }
    

    In this example, pair_sequence does not take additional arguments. If it needs to, std::bind or a lambda should be used to generate a function object that takes only one argument (of push_type), when it is passed to the coro_t::pull_type constructor.

提交回复
热议问题