【发布时间】:2018-01-24 10:17:53
【问题描述】:
我在将 boost::bind 与存储在 std::function 中的函数一起使用时遇到问题。
这与 boost::asio 有关:我正在构建一个基本的 UDP 服务器。 所以,首先让我们看看一些编译良好的代码没有 std::function(完整代码on Coliru here,取消注释定义以查看问题):
这里只有相关部分:
class udp_server
{
void start_receive()
{
_socket.async_receive_from(
boost::asio::buffer( _buffer ),
_remote_endpoint,
boost::bind(
&udp_server::_rx_handler,
this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred,
42
)
);
}
void _rx_handler( const boost::system::error_code&, std::size_t bytes_rx, int );
};
如您所见,我将处理程序_rx_handler(又名“回调”)传递给 boost::asio 函数,以便在收到某些内容时调用该函数。
由于我需要第三个参数并且“asio”函数需要特定的函数签名,因此我使用的是 boost::bind。到目前为止一切顺利。
现在,我想将这个类继承到另一个类中,在那里我可以定义一些更具体的事情来接收数据。 所以我在基类中用 std::function 替换处理程序,具有相同的签名:
std::function< void( const boost::system::error_code&, std::size_t bytes_rx, int )> _rx_handler;
或者,更方便的是,使用 typedef;
typedef std::function< void( const boost::system::error_code&, std::size_t bytes_rx, int ) > CALLBACK_T;
...
CALLBACK_T _rx_handler;
这样(我想),我可以添加一个成员函数来分配继承类中的任何成员函数:
void assignCallback( CALLBACK_T f )
{
_rx_handler = f;
}
不幸的是,这不能编译。 GCC 5.4.1 说:
/usr/include/boost/bind/bind.hpp:69:37: 错误:'std::function udp_server::*' 不是类、结构或联合类型
但是当我查看cppreference 时,我读到它是一个类模板...
查看此页面后,我还尝试使用target()访问函数上的指针:
boost::bind(
&udp_server::_rx_handler.target(),
this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred,
42
)
但这也不编译:
错误:没有匹配的函数调用‘std::function::target()’ udp_server::_rx_handler.target(),
问题:这里有什么问题?我认为“真正的”函数和 std::function 是可以互换的? 我怎样才能做到这一点?
附录:我觉得这可能与我对整个绑定的工作原理缺乏了解有关,所以感谢您的任何见解!
可能相关:std::function and std::bind: what are they & when they should be used?
【问题讨论】:
-
您的
std::function不再是成员函数,因此在调用boost::bind时不需要this参数。
标签: c++ function boost boost-bind