Boost logo

Boost Users :

Subject: Re: [Boost-users] boost::asio::asyn_accept handler
From: Gavin Lambert (gavinl_at_[hidden])
Date: 2017-03-29 02:23:34


On 29/03/2017 12:02, Christopher Pisz via Boost-users wrote:
> Sigh. I know that code wouldn't work. That is my interpretation of what you
> gave me. Now you are talking about two arguments and placeholders, but why
> would I give it a place holder, when I am giving it the argument directly?
> the tcp_connection::pointer argument is new_connection. The placeholder is
> for the error code which I am not supplying directly. Either way, it still
> fails to compile if you add a std::placeholders::_2 on the end.

You need _1 (and only that) in the functor that is passed to
async_accept, since that expects a callback that takes exactly one
error_code argument.

You might need other placeholders if elsewhere you're using functors
that take more than one argument, as in one previous instance where you
were using multiple binds or getting a callback passed in externally to
then rebind locally.

> Can we just get a compilable working example of the following method while
> maintaining the use of the std::function variable? I don't want to bind
> directly, I don't want to use lambda, I want to have an std::function
> variable that I can pass to others. It's really a simple 6 line problem....

Just be careful with passing functions outside of the class, as they can
have hidden dependencies (eg. the below will UB or crash if something
tries to call the callback after tcp_server has been destroyed).

> The following code still fails to compile:
>
> void start_accept()
> {
> tcp_connection::pointer new_connection =
> tcp_connection::create(acceptor_.get_io_service());
>
> std::function<void(tcp_connection::pointer new_connection, const
> boost::system::error_code &amp; error)> callback =
> std::bind(&tcp_server::handle_accept, this, new_connection,
> std::placeholders::_1);
>
> acceptor_.async_accept(new_connection->socket(), callback);
> }

I still can't see your monitor from where I'm sitting, so I don't know
what errors it produces. If you want anything more helpful than
guesswork, then tell people what the errors are; don't just say that it
fails. (http://www.catb.org/esr/faqs/smart-questions.html)

First off, is that &amp; actually in your source code or is it only
being added when you email? You need to fix that if it's actually in
your code.

Secondly, you shouldn't specify parameter names in the type signature of
std::function; just use types.

Otherwise, that code looks like it should work, assuming handle_accept
has a compatible signature.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net