簡體   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