How to use lambda to for boost asio async completion handler

#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

void print(boost::asio::deadline_timer* t, int* count)
{
    if (*count < 5)
    {
        std::cout << *count << "\n";
        ++(*count);

        t->expires_at(t->expires_at() + boost::posix_time::seconds(1));
        t->async_wait(boost::bind(print, t, count));
    }
}

int main()
{
    boost::asio::io_service io;

    int count = 0;
    boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));
//    t.async_wait(boost::bind(print, &t, &count));
    t.async_wait([&]{ // compile error occurred
        print(&t, &count);
    });

    io.run();

    std::cout << "Final count is " << count << "\n";

    return 0;
}

What's the different between bind and lambda exp.? I guess it's OK in syntax, the problem is async_wait need a function object with param "const boost::system::error_code& e".

Answers


I don't know asio very well, but adding the requested parameter fixes the issue.

t.async_wait([&] ( const boost::system::error_code& ) {
    print(&t, &count);
});

It looks like a quirk or bug of Boost.Bind allows additional, ignored arguments to a bind expression generated from a function pointer. It's probably better not to rely on this, but to explicitly accept and discard the error code.


Need Your Help

Loading random Stylesheets into a single HTML using jquery

jquery html css random

I intend on doing a very simple webpage that changes appearance every time it is loaded. I want to have only one HTML document. It can either be linked to one of several stylesheets (randomly selec...

Combining multiple tables with r.union in RethinkDB

rethinkdb rethinkdb-javascript

I will be dynamically combining a range of tables with the exact same structure in RethinkDB.