Cannot store bind::front::handler returned value in variable

  boost, boost-beast, c++, stdbind

With these present in other parts of my codebase,

namespace net = boost::asio;
using boost::asio::ip::tcp;

boost::asio::io_context& io_context_;
tcp::acceptor acceptor_;
void server::on_accept(boost::beast::error_code ec, boost::asio::ip::tcp::socket socket);

I have noticed that this piece of code compiles:

auto strand = net::make_strand(io_context_);
std::shared_ptr<server> this_pointer = shared_from_this();

acceptor_.async_accept(
    strand,
    boost::beast::bind_front_handler(&server::on_accept, this_pointer)
);

whereas this does not:

auto strand = net::make_strand(io_context_);
std::shared_ptr<server> this_pointer = shared_from_this();

auto call_next = boost::beast::bind_front_handler(&server::on_accept, this_pointer);

acceptor_.async_accept(
    strand,
    call_next
);

and it fails with the error

/usr/include/boost/beast/core/detail/bind_handler.hpp:251:45: error: cannot convert ‘boost::beast::detail::bind_front_wrapper<void (server::*)(boost::system::error_code, boost::asio::basic_stream_socket<boost::asio::ip::tcp>), std::shared_ptr<server> >’ to ‘void (server::*)(boost::system::error_code, boost::asio::basic_stream_socket<boost::asio::ip::tcp>)’ in initialization
  251 |         , args_(std::forward<Args_>(args)...)

I am very curious why passing the value returned from bind_front_handler directly to the async_accept would work but storing that value in a variable and then passing that variable would not work.

I also understand very little about Boost and Beast right now, but here it appears to me like I am forgetting something very basic about C++ itself. Why are both of those piece of code not equivalent?

Source: Windows Questions C++

LEAVE A COMMENT