c++ - 如何使用 lambda 来 boost asio 异步完成处理程序

标签 c++ boost lambda 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;
}

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".

最佳答案

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

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

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

关于c++ - 如何使用 lambda 来 boost asio 异步完成处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22314673/

相关文章:

boost - C++ 中的区间映射

java - 使用可选映射和过滤器重写 if 语句

java - 带大括号的流 api

c++ - 为什么我不能从 C++ 中的模板化父类(super class)继承?

c++ - 在单元测试框架内循环

c++ - 使用 ptr_vector 时访问派生类的方法

c++ - 如何使用 boost::spirit 将单词序列解析为 vector ?

python - f = lambda n :(1, f(n-1)*n)[n>1] 在 Python 3 中给出 RunTimeError

c++ - OpenGl翻译

c++ - C++ 中的编译时接口(interface)实现检查