Search code examples
boostboost-asio

Boost::asio async_wait handler signature


I am going through the boost::asio examples. I am looking at Example 4

What is confusing is that, the WaitHandler in this example has the signature

void print (this)

But the async_wait call expects a handler whose

function signature of the handler must be:

void handler( const boost::system::error_code& error // Result of operation. );

Source: Boost documentation

Since the parameter type is part of a function's signature, why in the example above, async_wait accepts a handler whose parameter is not of type boost::system::error_code?

THanks.


Solution

  • As you correctly observe, the async_wait method accepts a handler function which takes one parameter (const boost::system::error_code&). But in the Timer.4 example, the call to async_wait is passed via boost bind as follows:

    timer_.async_wait(boost::bind(&printer::print, this));
    

    The boost::bind returns a function object which refers to method print for class printer for the object referenced by this. This function object is called by the async_wait method with the error parameter (since that is the signature it expects). But the error parameter is silently ignored because it is not referenced by the bind.

    The official boost::bind documentation provides more details on boost::bind. See also the article How the Boost Bind Library Can Improve Your C++ Programs (there are probably many more articles available but I found this one very useful).