使用不带lambda的boost coroutine2

时间:2017-01-22 20:46:03

标签: c++ boost boost-bind boost-coroutine2

我想这是我第一次无法在这里找到已经回答的问题,如果有人成功使用了没有lambda的boost coroutine2 lib,我真的可以使用一些帮助。 我的问题,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
}
};

我打算在另一个类中使用它作为协同程序,它的任务是将每个产生的值放在其位置,所以我试图实例化一个对象:

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

但不会编译:

/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> > > >&)’

有人可以解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

这与Boost Coroutine无关。

它只是与成员函数绑定。您忘记公开未绑定的参数:

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();
    }
}

打印

42
42.42
+042.42