chriskohlhoff / asio

Asio C++ Library
http://think-async.com/Asio
4.98k stars 1.22k forks source link

Fix the compilation error of ssl async_handshake function #1389

Closed zhllxt closed 11 months ago

zhllxt commented 11 months ago
#include <cstdlib>
#include <functional>
#include <iostream>
#include "asio.hpp"
#include "asio/ssl.hpp"
#include "asio/experimental/co_composed.hpp"

using namespace asio;
using asio::ip::tcp;

using tcp_socket = asio::as_tuple_t<asio::use_awaitable_t<>>::as_default_on_t<asio::ip::tcp::socket>;

constexpr auto use_nothrow_deferred = asio::as_tuple(asio::deferred);

struct ssl_async_handshake_op
{
    auto operator()(auto state, auto stream_ref,
        asio::ssl::stream_base::handshake_type handsk_type) -> void
    {
        auto& ssl_stream = stream_ref.get();

        // ... 

        auto [e1] = co_await ssl_stream.async_handshake(handsk_type, use_nothrow_deferred);

        co_return e1;
    }
};

template <
    typename SslStream,
    typename HandshakeToken =
        typename ::asio::default_completion_token<
            typename SslStream::executor_type>::type>
    inline auto async_handshake(
        SslStream& ssl_stream,
        asio::ssl::stream_base::handshake_type handsk_type,
        HandshakeToken&& token =
        typename ::asio::default_completion_token<
        typename SslStream::executor_type>::type())
{
    return async_initiate<HandshakeToken, void(asio::error_code)>(
        experimental::co_composed<void(asio::error_code)>(
            ssl_async_handshake_op{}, ssl_stream),
        token,
        std::ref(ssl_stream), handsk_type);
}

asio::awaitable<void> do_test(asio::ssl::stream<tcp_socket&>& stream)
{
    co_await async_handshake(stream, asio::ssl::stream_base::server);
}

int main()
{
    asio::io_context ioc;
    tcp_socket sock(ioc);
    asio::ssl::context sslctx(asio::ssl::context::sslv23);
    asio::ssl::stream<tcp_socket&> stream(sock, sslctx);

    asio::co_spawn(ioc.get_executor(), do_test(stream), asio::detached);

    return 0;
}

compile error info:

"asio::experimental::detail::co_composed_promise<Executors,Handler,Return>::await_transform": no matching overloaded function found