在没有 lambda 的情况下使用 boost coroutine2

Use of boost coroutine2 without lambdas

我想这是我第一次无法在这里找到已经回答的问题,如果有人在没有 lambda 的情况下成功使用了 boost coroutine2 lib,我真的需要一些帮助。 我的问题,总结:

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

我打算将其用作另一个 class 内部的协程,其任务是将每个产生的值放在其位置,因此我尝试实例化一个对象:

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

有人可以阐明这个问题吗?

这与 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