Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 301
navigator Avatar asked Nov 22 '09 15:11

navigator


2 Answers

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).

like image 83
Yukiko Avatar answered Nov 05 '22 13:11

Yukiko


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.

like image 2
Nitramk Avatar answered Nov 05 '22 12:11

Nitramk