TheWaterProgrammer
TheWaterProgrammer

Reputation: 8239

Passing a lambda with return value into a callback without return value

This question involves boost::asio but is a pure C++ 11 question.

I am new to C++ 11 & lambda techniques which I am trying to use with boost::asio::async_connect for network communication.

Following is my function which attempts an asynchronous connect with the host.

bool MyAsyncConnectFunction() {

  //some logic here to check validity of host
  if (ip_is_not_resolved)
    return false;

  the_socket.reset(new tcp::socket(the_io_service));
  auto my_connection_handler = [this]
        (const boost::system::error_code& errc, const tcp::resolver::iterator& itr)
  {
    if (errc) {
        //Set some variables to false as we are not connected
        return false;
    }

    //Do some stuff as we are successfully connected at this point
    return true;
  };

  //How is async_connect taking a lambda which 
  boost::asio::async_connect(the_socket, IP_destination, tcp::resolver::iterator(), my_connection_handler);
  return true;
}

All works fine. There are no functional issues absolutely. However, I am wondering that boost::asio::async_connect takes a ConnectionHandler without a return type in its last parameter but I am passing a lambda i.e. my_connection_handler which returns a value.

How is it possible that I can pass a lambda with a return value whereas boost::asio::async_connect's 4th param takes a callback without a return value ?

Upvotes: 1

Views: 600

Answers (1)

Jean-Bernard Jansen
Jean-Bernard Jansen

Reputation: 7872

boost::asio::async_connect is a function template that takes a callable as its fourth argument. It does not use the return value of said callable, nor does it care about it. Just as you could write :

auto f = []() { return true; };
f();  // Return value is discarded

The example of @m.s. is good too. Since it is a template, the function resolves the argument according to the template argument deduction rules.

Upvotes: 2

Related Questions