【问题标题】:How to call boost::asio async functions如何调用 boost::asio 异步函数
【发布时间】:2013-05-28 14:09:42
【问题描述】:

我想在我的异步调用中使用 boost::asio deadtime_timer。我想在调用对象上调用函数 A::fun(0)。要做到这一点,我会这样做:

io_service io;
deadline_timer timer(io, boost::posix_time::seconds(10));
timer.async_wait(&A::fun, this, 0); //error
io.run();

在第二行我得到了错误:basic_deadline_timer::async_wait(const WaitHandler &)' : 需要 1 个参数 - 2 个提供。

我在某些任务上使用了与启动 boost::threads 相同的语法,我认为它会起作用。

【问题讨论】:

标签: c++ boost boost-asio


【解决方案1】:

你需要传递一个满足WaitHandler要求的函数对象;也就是说,它接受错误代码作为其参数。

在 C++11 中,我会使用 lambda:

timer.async_wait([this](const boost::system::error_code &){fun(0);});

在 C++03 中,使用 Boost.Bind 制作函数对象:

timer.async_wait(bind(&A::fun, this, 0));

在任何一种情况下,您都可能希望检查传递的错误代码(在第二种情况下,通过修改或包装fun)以确保计时器确实已过期。

【讨论】:

  • 没错。但是我该如何使用它来调用带有 3 个参数的函数呢? timer.async_wait(boost::bind(&FileSystem::Open, this, pathname, openMode, filePerm)) 会引发 89 个错误。
  • @cygi1989:应该没问题,如果*thisFileSystemOpen 确实需要三个参数。 Open 是如何声明的?前几个错误是什么?
  • virtual int Open(const char* pathname, int openMode, int filePerm = 0)。我正在基类中实现该方法(这是抽象的)。错误 C2780: 'boost::_bi::bind_t<:dm_result>::type,boost::_mfi::dm,_bi::list_av_1:: type> boost::bind(M T::* ,A1)' :需要 2 个参数 - 提供 5 个参数,请参见“boost::bind”错误 C2780 的声明:“boost::_bi::bind_t,_bi::list_av_9::type > boost::bind(boost::type,R (__thiscall T::* )(B1,B2,B3,B4,B5,B6,B7,B8) const,A1,A2,A3,A4,A5 ,A6,A7,A8,A9)' : expect11
  • 无论如何,另一种只采用一个 int 参数的方法工作正常
  • @cygi1989:也许你可以用足够的代码更新问题来重现问题;很难猜出这里出了什么问题。也许还有Open 的另一个重载?
猜你喜欢
  • 2020-11-06
  • 2018-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-05
  • 1970-01-01
相关资源
最近更新 更多