#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/