1. 程式人生 > 實用技巧 >關於C++中的bind函式

關於C++中的bind函式

在muduo網路庫中出現這樣的呼叫:

 timerfdChannel_.setReadCallback(
        std::bind(&PeriodicTimer::handleRead, this));

這裡的

PeriodicTimer::handleRead

的定義如下:

  void handleRead()
  {
    loop_->assertInLoopThread();
    muduo::net::detail::readTimerfd(timerfd_, Timestamp::now());
    if (cb_)
      cb_();
  }

而setReadCallbackd的定義如下:

  void setReadCallback(ReadEventCallback cb)
  { readCallback_ = std::move(cb); }

其中setReadCallback的定義如下:

typedef std::function<void(Timestamp)> ReadEventCallback;

觀察發現,這裡將一個無引數的可呼叫物件,繫結到了一個要求有一個Timestamp引數的可呼叫物件上,特別奇怪。

經過查閱資料:

http://www.boost.org/doc/libs/1_56_0/libs/bind/bind.html

中記載:

Any extra arguments are silently ignored, just like the first and the second argument are ignored in the third example.

原因分析:

這裡setReadCallback確實是需要一個帶有Timestamp引數的物件的函式作為引數,但是經過bind繫結的可呼叫物件對引數個數並沒有限制。

當將bind產生的新物件被呼叫時的引數個數大於繫結時的規定,那麼多餘的引數將被忽略,於是就出現了這個例子的情況。