c++ - 我可以使用 boost::bind 来存储不相关的对象吗?

标签 c++ visual-c++ boost boost-asio boost-bind

我可以使用 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/

相关文章:

c++ - 如何在 multi_index_container 中添加指定的有序唯一索引

c++ - 如何查找 ActiveX 控件生成的事件的调度 ID

windows - 是否可以将断点条件设置为 "break when called by another thread"?

c++ - 静态初始化的问题

c++ - 为什么 "non-standard syntax; use ' &' to create a pointer to member"在 CTOR 中使用线程?

c++ - boost::numeric::quadrature 或 gsl quadrature 中的加权函数

c++ - 为什么在 Visual Studio 2008/2010 中_不需要 typename?

c++ - 虚函数是在编译期间确定的吗?

c++ - 如何对整数数组实现归并排序?

c++ - 如何使用 clang++ 链接到 boost in/usr/local 编译?