【问题标题】:Using boost:bind to bind a std::function使用 boost:bind 绑定一个 std::function
【发布时间】: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


【解决方案1】:

你的绑定应该修改如下:

void start_receive()
{
    _socket.async_receive_from(
        boost::asio::buffer( _buffer ),
        _remote_endpoint,
        boost::bind(
            udp_server::_rx_handler,
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred,
            42
        )
    );
}

您将 _rx_handlervoid (udp_server::*)(const boost::system::error_code&amp;, std::size_t bytes_rx, int); 更改为 std::function&lt;void(const boost::system::error_code&amp;, std::size_t bytes_rx, int)&gt;

因此您不再需要将实例绑定到udp_server

【讨论】:

  • 让我误会的是,从技术上讲,_rx_handler 仍然是班级成员。谢谢!
猜你喜欢
  • 2012-07-07
  • 1970-01-01
  • 1970-01-01
  • 2012-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多