使用boost :: function和boost :: bind与boost :: asio的错误

时间:2014-12-19 16:01:28

标签: boost-asio boost-bind boost-function

我遇到了将boost :: function与boost :: bind和boost :: asio结合起来的问题。我正面临代码片段,编译器抛出大量错误,我正在粘贴根错误。

static void
startAccept(boost::asio::io_service &io,
        boost::asio::ssl::context &ctx,
        boost::asio::ip::tcp::acceptor &acceptor_,
        const boost::system::error_code &ec
        )
{
    //details omitted for brevity reasons.
    return;
}
 boost::function<void(
                boost::asio::io_service &,
                boost::asio::ssl::context &,
                boost::asio::ip::tcp::acceptor &,
                boost::system::error_code &
                )> f;
        f = boost::bind(&startAccept,
                boost::ref(io),
                boost::ref(ctx),
                boost::ref(acceptor_), 
                boost::asio::placeholders::error);

错误:

In file included from as.cc:5:
In file included from /usr/local/include/boost/bind.hpp:22:
/usr/local/include/boost/bind/bind.hpp:457:93: error: no viable conversion from 'boost::asio::io_service' to
      'const boost::system::error_code'
        unwrapper<F>::unwrap(f, 0)(a[base_type::a1_], a[base_type::a2_], a[base_type::a3_], a[base_type::a4_]);
                                                                                            ^~~~~~~~~~~~~~~~~
/usr/local/include/boost/system/error_code.hpp:317:11: note: candidate constructor (the implicit copy constructor) not viable: no known
      conversion from 'boost::asio::io_service' to 'const boost::system::error_code &' for 1st argument
    class error_code
          ^
/usr/local/include/boost/system/error_code.hpp:317:11: note: candidate constructor (the implicit move constructor) not viable: no known
      conversion from 'boost::asio::io_service' to 'boost::system::error_code &&' for 1st argument
    class error_code
          ^

为什么编译器试图将boost :: asio :: io_service转换为boost :: system :: error_code?

1 个答案:

答案 0 :(得分:2)

由于签名已经匹配,因此在分配给boost :: function时不需要使用boost :: bind:

#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>

static void startAccept(boost::asio::io_service &io, boost::asio::ssl::context &ctx,
                        boost::asio::ip::tcp::acceptor &acceptor_, boost::system::error_code ec) {
    // details omitted for brevity reasons.
    return;
}

int main() {
    boost::function<void(boost::asio::io_service &, boost::asio::ssl::context &, boost::asio::ip::tcp::acceptor &,
            boost::system::error_code)> f;

    f = &startAccept;
}

请注意,我更改了最后一个参数,因为它在const&amp; /&amp;中不匹配。湖。但这不是问题。

绑定第一个参数后,绑定签名将成为一元函数。这可能是您想要作为完成处理程序传递的内容(取决于完成处理程序签名应该是什么):

object.async_operation(bufs, boost::bind(f,
            boost::ref(io), boost::ref(ctx), boost::ref(acceptor_),
            boost::asio::placeholders::error))

在这种情况下,它是一个完整的处理程序,与boost::function<void(boost::system::error_code)>

兼容