如何使用 lambda 来提升 asio 异步完成处理程序

met*_*et7 7 c++ lambda boost bind boost-asio

#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;
}
Run Code Online (Sandbox Code Playgroud)

bind 和 lambda exp 之间有什么区别?我想语法没问题,问题是 async_wait 需要一个带有参数“const boost::system::error_code& e”的函数对象。

Pot*_*ter 5

我不太了解 asio,但添加请求的参数可以解决问题。

t.async_wait([&] ( const boost::system::error_code& ) {
    print(&t, &count);
});
Run Code Online (Sandbox Code Playgroud)

它看起来像是 Boost.Bind 的一个怪癖或错误,它允许从函数指针生成的绑定表达式中使用额外的、被忽略的参数。最好不要依赖于此,而是明确接受并丢弃错误代码。