boost :: bind如何定义一个将回调作为参数的函数

时间:2017-07-10 03:42:19

标签: c++ boost-asio

我正在尝试编写一个调用boost :: asio操作的库模块。应用程序逻辑层将使用该模块进行进一步处理,具体取决于结果。

我的要求简单明了。我需要的是能够在下面的我的Util类中指定一个回调fn,它可以接受任何函数ptr,或者boost :: bind(成员fn)等等,并在异步代码完成后调用该回调

class Util {
  public:
    void sendMsg(const Msg& m, <some callback fn here...>) {
       // Make a call to boost::asio approximately as below..
       boost::asio::async_write(socket_, boost::asio::buffer(message_),
                   boost::bind(&tcp_connection::handle_write, shared_from_this(),
                   boost::asio::placeholders::error,
                    boost::asio::placeholders::bytes_transferred));

      // Here, I want to pass the "<some callback fn here>" to async_write,
      // instead of calling boost::bind here.  How to do that?
    }
};

所以,我的具体问题是...... 我的sendMsg签名应该是什么样的?我无法到达fn签名,尤其是回调部分。

感谢任何让我知道如何做到这一点的人。

1 个答案:

答案 0 :(得分:0)

如果您可以访问lambdas,那很简单

class Util {
  public:
    template <typename _Proc>
    void sendMsg(const Msg& m, _Proc proc) 
    {
        shared_ptr<Util> pThis = shared_from_this;
        boost::asio::async_write(socket_, boost::asio::buffer(message_),
            [&proc, =pThis/* , etra args */](boost::...::error_code ec, size_t bytes) // <- use capture to pass extra agruments and shared ptr
            {
               // use pThis !
               proc(/* etra args */);
               // or pthis->proc()
            });
        }

};

这将接受lambdas以及std / boost :: function