将具有 return 值的 lambda 传递给没有 return 值的回调
Passing a lambda with return value into a callback without return value
本题涉及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
,其中 return 是一个值。
我怎么可能传递带有 return 值的 lambda 而 boost::asio::async_connect
的第 4 个参数在没有 return 值的情况下接受回调?
boost::asio::async_connect
是一个函数模板,它接受一个可调用对象作为它的第四个参数。它不使用所述可调用对象的 return 值,也不关心它。就像你可以写的那样:
auto f = []() { return true; };
f(); // Return value is discarded
@m.s的例子。也很好。由于它是模板,函数根据 template argument deduction rules.
解析参数
本题涉及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
,其中 return 是一个值。
我怎么可能传递带有 return 值的 lambda 而 boost::asio::async_connect
的第 4 个参数在没有 return 值的情况下接受回调?
boost::asio::async_connect
是一个函数模板,它接受一个可调用对象作为它的第四个参数。它不使用所述可调用对象的 return 值,也不关心它。就像你可以写的那样:
auto f = []() { return true; };
f(); // Return value is discarded
@m.s的例子。也很好。由于它是模板,函数根据 template argument deduction rules.
解析参数