boost::asio 如何将成员函数传递给 acceptor.async_accept()

boost::asio how to pass member function to acceptor.async_accept()

我试图将成员函数作为 AcceptHandler 传递给 boost::asio 的 async_accept() 方法。我收到一条编译错误消息:

AcceptHandler type requirements not met

来自链接行:

// If you get an error on the following line it means that your handler does not meet the documented type requirements for a AcceptHandler.

documentation 表示处理程序必须如下所示:

void accept_handler(const boost::system::error_code& error) //documentation
{
  if (!error)
  {
    // Accept succeeded.
  }
}

我的成员函数如下所示:

void WifiConnector::onAccept(const boost::system::error_code &ec) //my code
{
    if (ec) {
        std::cout << ec.message();
        return;
    }
    socket.async_read_some(boost::asio::buffer(mBuffer), &WifiConnector::readHandler);
}

我觉得这没什么区别。

但我必须这样调用 acceptor.async_accept() 方法:

acceptor.async_accept(socket, &WifiConnector::onAccept); //my code

而不是

acceptor.async_accept(socket, accept_handler); //documentation

因为我假设它是一个成员函数。如果我尝试像文档建议的那样传递它:

acceptor.async_accept(socket, onAccept); //my code

出现错误提示:没有重载函数的实例。

错误是因为我以错误的方式传递成员函数还是我做错了什么?

编辑: 我正在从包含接受器等的对象中调用 async_accept() 方法

Is the error because I am passing the member function in the wrong way or what am I doing wrong?

调用普通函数和调用(非静态)成员函数是有区别的。后一个只能与适当的对象一起调用。因此,您必须使用多种方式中的一种来转接呼叫。最简单的方法是使用 lambda:

WifiConnector wifi;
...
acceptor.async_accept(socket, [&wifi] (const auto& ec) { wifi.onAccept(ec); } );

但是请注意,您必须认真考虑您的 wifi 对象的生命周期,因为其他线程现在可以通过引用访问它并依赖于拥有线程使该对象保持活动状态。例如,传递 shared_ptrweak_ptr 对象而不是普通引用(可能会悬垂)在 asio 回调中并不罕见。

boost文档明确提到如何将非静态方法传递给接受器here

以上摘录link:

void my_class::accept_handler(
    const boost::system::error_code& ec)
{
  ...
}
...
acceptor.async_accept(...,
    boost::bind(&my_class::accept_handler,
      this, boost::asio::placeholders::error));

如果您的 class.

,您可以用实例替换 this