On 18/03/2015 14:23, Andrew Hundt wrote:
In C++11 is there an easy way to use boost::asio::io_service::strand::wrap() on a lambda function handling the return of an async_receive call?
As noted in the docs (link below it looks like there has to be an implementation of asio_handler_invoke but I'm not sure how that would work for a lambda function. Looking through the C++11 examples I can't find any examples of using a strand. Any help would be greatly appreciated.
http://www.boost.org/doc/libs/1_57_0/doc/html/boost_asio/overview/core/stran...
You only need to define asio_handler_invoke if something more complicated than simply trying the call operator is required to invoke your handler object type. strand::wrap defines asio_handler_invoke for you such that intermediate handlers still route through the strand. So all you should need to do is: async_read(mysocket, buffers, mystrand.wrap([=](const error_code& ec, size_t count) { // ... })); (It's important to copy captured variables, as by the time the handler is called the original function will have exited.) Having said this, using lambdas can get tricky in real-world code, as it's common to want to start the same read operation when the first completes, and so on. Unless you're very careful this can quickly get messy. Using coroutines can sometimes help with this, if you're familiar with them already.