如何使用lambda来boost异步完成处理程序

How to use lambda to for boost asio async completion handler

本文关键字:处理 程序 异步 boost 何使用 lambda      更新时间:2023-10-16
#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;
}

bind和lambda exp有什么不同?我想这在语法上是可以的,问题是async_wait需要一个参数为const boost::system::error_code&e"。

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

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

这看起来像是Boost的一个怪癖或bug。Bind允许对从函数指针生成的绑定表达式使用附加的、被忽略的参数。最好不要依赖它,而是显式地接受并丢弃错误代码。