C ++ / Boost:将成员函数作为参数传递给boost :: bind

时间:2013-12-05 05:40:22

标签: c++ boost

我对C ++很陌生,所以请不要评判我: - )

我有一个名为connection的课程,其中包括以下方法:

    void connection::handle_connect(const boost::system::error_code& err) {
        if (!err) {
            boost::asio::async_write(socket_, request_,
                boost::bind(&connection::handle_write_request, this,
                boost::asio::placeholders::error, &connection::handle_read_status_line));
        } else {
            std::cout << "Error in handle_connect: " << err.message() << "\n";
        }
    }

    void connection::handle_write_request(const boost::system::error_code& err, boost::function<void(const boost::system::error_code&)> callback) {
        if (!err) {
            boost::asio::async_read_until(socket_, response_, 0,
                boost::bind(&callback, this,
                boost::asio::placeholders::error));
        } else {
            std::cout << "Error in handle_write_request: " << err.message() << "\n";
        }
    }

    void connection::handle_read_status_line(const boost::system::error_code& err) {
        if (!err) {
            std::istream response_stream(&response_);
            std::string response;
            std::getline(response_stream, response);
            std::cout << "Response: " << response << std::endl;
        } else {
            std::cout << "Error in handle_read_status_line: " << err << "\n";
        }
    }

我试图让handle_write_request方法变得更加通用。我已将callback添加到其签名中 - 这应该是传递给boost::bind的方法的地址,并在boost::asio::async_read_until中称为回调。

然而,这甚至无法编译:-) MSVS2013正在说

    Error   1   error C2825: 'F': must be a class or namespace when followed by '::'    C:\local\boost_1_55_0\boost\bind\bind.hpp   69  1   driver
    Error   2   error C2039: 'result_type' : is not a member of '`global namespace''    C:\local\boost_1_55_0\boost\bind\bind.hpp   69  1   driver
    Error   3   error C2146: syntax error : missing ';' before identifier 'type'    C:\local\boost_1_55_0\boost\bind\bind.hpp   69  1   driver
    Error   4   error C2208: 'boost::_bi::type' : no members defined using this type C:\local\boost_1_55_0\boost\bind\bind.hpp  69  1   driver
    Error   5   error C1903: unable to recover from previous error(s); stopping compilation C:\local\boost_1_55_0\boost\bind\bind.hpp   69  1   driver

我应该如何正确传递成员函数的地址?我会很感激任何建议!

1 个答案:

答案 0 :(得分:2)

要绑定类的成员函数,请执行以下操作:

boost::bind(&SomeClass::SomeMemberFunc, this, params...);

在您的情况下,callback已经是一个仿函数,因此请尝试boost::bind(callback, this, <some proper parameter>);