c++ - 将 boost phoenix lambda 与 io_service 一起使用

标签 c++ boost lambda boost-phoenix

我正在使用 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::arg1arg2 ...)。

但是,只需替换 boost::bindstd::bind , boost::lambda::bindboost::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/

相关文章:

c++ - 讨论了哪些 boost 库包含在 C++17 中?

使用 lambda 的 c++11 排序列表

c# - 我希望能够使用 lambda 表达式来指定要通过 wcf 服务返回的值范围

c++ - float 的指数偏差有规范吗?

c++ - 将 malloc/free 与类一起使用

c++ - 由静态方法(或工厂(?))创建的 boost python 对象中的虚拟覆盖

C++ set::find by 对象属性

Java 8 Lambda Sort With Variable 方法引用

c++ - 学习和跨平台开发 (C++)

javascript - 如何计算需要多少位来表示任何负值?