c++boostboost-bindboost-coroutine2

Use of boost coroutine2 without lambdas


I guess this is the first time I couldn't manage to find an already answered question in here, and I could really use some help if anyone have successfully used boost coroutine2 lib without lambdas. My problem, sumarized:

class worker {
...
void import_data(boost::coroutines2::coroutine
<boost::variant<long, long long, double, std::string> >::push_type& sink) {
...
sink(stol(fieldbuffer));
...
sink(stod(fieldbuffer));
...
sink(fieldbuffer); //Fieldbuffer is a std::string
}
};

I intend to use this as a coroutine from inside another class, that has the task of putting each yielded value in its place, so I tried to instantiate an object:

worker _data_loader;
boost::coroutines2::coroutine<boost::variant<long, long long, double, string>>::pull_type _fieldloader
        (boost::bind(&worker::import_data, &_data_loader));

but that wont compile:

/usr/include/boost/bind/mem_fn.hpp:342:23:
error: invalid use of non-static member function of type 
‘void (worker::)(boost::coroutines2::detail::push_coroutine<boost::variant<long int, long long int, double, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > >&)’

Could someone shed any light in this problem?


Solution

  • This has nothing to do with Boost Coroutine.

    It is just about bind with a member function. You forgot to expose the unbound parameter:

    boost::bind(&worker::import_data, &_data_loader, _1)
    

    Live On Coliru

    #include <boost/coroutine2/all.hpp>
    #include <boost/variant.hpp>
    #include <boost/bind.hpp>
    #include <string>
    
    using V    = boost::variant<long, long long, double, std::string>;
    using Coro = boost::coroutines2::coroutine<V>;
    
    class worker {
      public:
        void import_data(Coro::push_type &sink) {
            sink(stol(fieldbuffer));
            sink(stod(fieldbuffer));
            sink(fieldbuffer); // Fieldbuffer is a std::string
        }
    
        std::string fieldbuffer = "+042.42";
    };
    
    #include <iostream>
    int main() 
    {
        worker _data_loader;
        Coro::pull_type _fieldloader(boost::bind(&worker::import_data, &_data_loader, _1));
    
        while (_fieldloader) {
            std::cout << _fieldloader.get() << "\n";
            _fieldloader();
        }
    }
    

    Prints

    42
    42.42
    +042.42