I want to reliaze how to use boost::aio::async_connect with lambda. Boost version 1.68
It's really strange that I could use std::bind but not lambda. If I use std::bind, it work. But when I use lambda, it buillt failed, and said "IteratorConnectHandler type requirements not met.
std::bind version (worked)
void SslClient::connect(boost::asio::ip::tcp::resolver::results_type results) {
auto sp = shared_from_this();
boost::asio::async_connect(ws->next_layer().next_layer(),
results.begin(),
results.end(),
std::bind(
on_connect,
std::placeholders::_1)
);
}
lambda version (not worked)
void SslClient::connect(boost::asio::ip::tcp::resolver::results_type results) {
auto sp = shared_from_this();
boost::asio::async_connect(ws->next_layer().next_layer(),
results.begin(),
results.end(),
[&, sp](boost::system::error_code ec) {
if (ec) {
return;
}
ws->next_layer().async_handshake(boost::asio::ssl::stream_base::client,
[&, sp](boost::system::error_code ec1) {
handShake(ec);
});
}
);
}
So how to use lambda here?
You call async_connect with pair of iterators, so your lambda should meet iterator connect handler requirements. As second parameter you have to pass connected endpoint.
To be consistent with reference you should also fix bind version.
on_connectshould also takeiteratoras second param.Your current
bindversion compiles and works, but when asynchronous operation initiated byasync_connectis completed, functor created bybindis called with onlyerror_code, you cannot accessendpoint. You can modify bind so that it takeson_connectwithout any arguments.this also compiles, but when handler is called neither
error_codenorendpointcan be accessed. (Yes it is a bit strange that you are not getting compiler errors when usingbindwhich inform that requirements of handler are not fulfilled. I don't know where this disagreement between lambda and bind comes from.)