繁体   English   中英

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

[英]boost::bind how to define a function that takes a callback as argument

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

我的要求很简单。 我需要做的就是能够在下面的Util类中指定一个回调fn,该回调可以接受任何函数ptr或boost :: bind(member 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签名,尤其是回调部分。

多亏有人让我知道该怎么做。

如果您可以访问lambda,这很容易

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

};

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM