C++11 将带返回值的lambda传递到不带返回值的回调中
这个问题涉及到C++11 将带返回值的lambda传递到不带返回值的回调中,c++11,boost,lambda,boost-asio,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.
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,但我传递了一个lambda,即返回值的my_connection_handler
我怎么可能传递带有返回值的lambda,而boost::asio::async_connect
的第四个参数接受回调而没有返回值?boost::asio::async_connect
是一个函数模板,它将可调用作为其第四个参数。它不使用所述callable的返回值,也不关心它。正如你可以写的那样:
auto f = []() { return true; };
f(); // Return value is discarded
@m.s.的例子也很好。因为它是一个模板,所以函数根据解析参数。返回值可以被丢弃,就像在这个简单的示例中一样:在asio中也是如此:@m.s.返回值被丢弃!!这是否意味着我可以将基于返回值的回调绑定到无效的返回回调?还是asio的connect_处理程序就是这样编写的?正如我说的,我是新手。抱歉,如果这是个愚蠢的问题不,不是。它之所以有效,是因为您不调用函数,而是调用了一个函数模板,该模板需要一个可调用的函数,无论其返回类型是什么。