将 lambda 与 Boost Beast 一起使用而不是绑定

Using lambdas with Boost Beast instead of bind

this example 中,如果我用绑定更改此调用:

boost::asio::async_connect(
        socket_,
        results.begin(),
        results.end(),
        std::bind(
            &session::on_connect,
            shared_from_this(),
            std::placeholders::_1));

为此:

    auto self = shared_from_this();
    boost::asio::async_connect(
                socket_,
                results.begin(),
                results.end(),
                [self](boost::system::error_code ec) {
        self->on_connect(ec);
    });

我收到断言错误:

boost/boost/asio/impl/connect.hpp:761: error: static_assert failed "IteratorConnectHandler type requirements not met"
  BOOST_ASIO_ITERATOR_CONNECT_HANDLER_CHECK(
  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

那里有一条评论:

// If you get an error on the following line it means that your handler does
// not meet the documented type requirements for a IteratorConnectHandler.

我个人don't prefer bind,想把它改成lambda。我做错了吗,或者这是 boost::beast 中的一个小错误?

顺便说一下,为 on_resolve 更改为 lambda 工作正常。

您的 lambda 参数数量与处理程序签名不匹配,根据参考 async_connect 处理程序采用 error_code 连接端点 - 它你的情况缺少。

修复:

auto self = shared_from_this();
boost::asio::async_connect(
            socket_,
            results.begin(),
            results.end(),
            [self](boost::system::error_code ec, boost::asio::ip::tcp::resolver::iterator) {
                                                 ^^^
    self->on_connect(ec);
});