我可以使用 boost::bind 使生成的函数对象存储一个未声明为绑定(bind)目标函数的参数的对象吗?例如:
void Connect(const error_code& errorCode)
{
...
}
// Invokes Connect after 5 seconds.
void DelayedConnect()
{
boost::shared_ptr<boost::asio::deadline_timer> timer =
boost::make_shared<boost::asio::deadline_timer>(ioServiceFromSomewhere);
timer->expires_from_now(
boost::posix_time::seconds(5));
// Here I would like to pass the smart pointer 'timer' to the 'bind function object'
// so that the deadline_timer is kept alive, even if it is not an actual argument
// to 'Connect'. Is this possible with the bind syntax or similar?
timer->async_wait(
boost::bind(&Connect, boost::asio::placeholders::error));
}
附言。我最感兴趣的是已经存在的这样做的语法。我知道我可以自己制作自定义代码。我也知道我可以手动保持计时器处于事件状态,但我想避免这种情况。
最佳答案
是的,您可以通过绑定(bind)额外的参数来做到这一点。我经常用 asio 做到这一点,例如为了在异步操作期间保持缓冲区或其他状态处于事件状态。
之后,您还可以通过扩展处理程序签名以使用它们来从处理程序访问这些额外的参数:
void Connect(const error_code& errorCode, boost::shared_ptr<asio::deadline_timer> timer)
{
}
timer.async_wait(
boost::bind(&Connect, boost::asio::placeholders::error, timer));
关于c++ - 我可以使用 boost::bind 来存储不相关的对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41934804/