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.
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).
You specify in the call to async_wait what parameters your callback function takes, using placeholders. Check the sentence just above the async_wait call on the page you linked to:
You will note that the boost::asio::placeholders::error placeholder is not specified here, as the print member function does not accept an error object as a parameter.
Search for "placeholder" in this example and you'll see how to do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With