gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:02:31 26 4
gpt4 key购买 nike

我是 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

如何正确传递成员函数的地址?如果有任何建议,我将不胜感激!

最佳答案

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

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

在你的例子中,callback已经是一个仿函数,所以尝试 boost::bind(callback, this, <some proper parameter>);

关于C++/Boost:将成员函数作为参数传递给 boost::bind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20392311/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com