将带有返回值的lambda传递给没有返回值的回调

时间:2016-12-21 08:53:39

标签: c++11 boost lambda boost-asio

此问题涉及boost::asio,但这是一个纯粹的C++ 11问题。

我是C++ 11&的新手我尝试使用lambda进行网络通信的boost::asio::async_connect技术。

以下是我的函数,它尝试与主机进行异步连接。

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;
}

一切正常。绝对没有功能问题。但是,我想知道boost::asio::async_connect在其最后一个参数中使用ConnectionHandler without a return type,但我传递了一个lambda,即my_connection_handler,它返回一个值。

我怎么可能传递一个带有返回值的lambda,而boost::asio::async_connect的第四个参数接受一个没有返回值的回调?

1 个答案:

答案 0 :(得分:2)

boost::asio::async_connect是一个函数模板,它将可调用作为其第四个参数。它不使用所述可调用的返回值,也不关心它。就像你写的那样:

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

@ m.s的例子。也很好。由于它是一个模板,该函数根据template argument deduction rules解析参数。