我正在使用 boost io_service 异步运行方法:
void my_class::completion_handler()
{
...
}
m_io_service.post(boost::bind(&my_class::completion_handler, this));
我想使用 lambda 表达式而不是 boost::bind(见下文)以避免为每个处理程序创建方法,但我使用的 C++ 编译器不完全支持 C++11:
m_io_service.post([this](){ ... });
是否可以通过使用 phoenix lambda 获得相同的行为?
谢谢。
最佳答案
是的,这是可能的。
最显着的区别是占位符(不要使用 std::place_holders::_1
、 _2
... 但要使用 boost::phoenix::arg_names::arg1
、 arg2
...)。
但是,只需替换 boost::bind
与 std::bind
, boost::lambda::bind
或 boost::phoenix::bind
当然最终是没用的。
相反,您可以使用 Phoenix actors 来编写“lambdas”,例如
namespace phx = boost::phoenix;
boost::mutex mx;
boost::condition_variable cv;
boost::unique_lock<boost::mutex> lk(mx);
vc.wait(lk, phx::ref(m_queue_size) > 0);
成员调用在这方面很棘手。
好消息是 Phoenix 附带了许多 STL 操作的实现,例如 size()
, empty()
, push_back()
等等
在此队列实现中类似使用 Phoenix:Boost group_threads Maximal number of parallel thread和例如asio::io_service and thread_group lifecycle issue ).
boost::fusion::function<>
您可以使用 BOOST_PHOENIX_ADAPT_FUNCTION
调整免费功能和函数对象 BOOST_PHOENIX_ADAPT_CALLABLE
.然而,在后一种情况下,使用 boost::fusion::function<>
可能更优雅。 :
struct MyType {
MyType()
: complete_(complete_f { this })
{ }
void doSomething() { }
private:
struct complete_f {
MyType* _this;
void operator()() const {
// do something with _this, e.g
this->doSomething();
}
};
boost::phoenix::function<complete_f> complete_;
};
关于c++ - 将 boost phoenix lambda 与 io_service 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48005615/