使用std::bind可以将可调用对象和参数一起绑定,绑定后的结果使用std::function进行保存,并延迟调用到任何我们需要的时候。但要注意原函数中的引用类型参数与指针类型的参数在参数传递时的不同:
1 .原函数
// 含引用类型参数
void Resource::onResolveRef(std::promise<int> &promiseResolve, boost::system::error_code, boost::asio::ip::tcp::resolver::results_type){
}
// 含指针类型参数
void Resource::onResolvePointer(std::shared_ptr<std::promise<int>> promiseResolve, boost::system::error_code errorCode, boost::asio::ip::tcp::resolver::results_type results){
}
2 .应用std::bind原函数对原函数进行包装
std::shared_future<std::shared_ptr<std::vector<unsigned char>>> Resource::get(const std::string &host, const std::string &port, const std::string &path)
{
std::shared_ptr<std::promise<int>> promiseShared = std::make_shared<std::promise<int>>();
//对“含有引用类型参数”的函数据包装
_resolver.async_resolve(host.c_str(), port.c_str(), std::bind(&Resource::onResolveRef, shared_from_this(), std::ref(*promiseShared), std::placeholders::_1, std::placeholders::_2));
//对“含有指针类型参数”的函数据包装
_resolver.async_resolve(host.c_str(), port.c_str(), std::bind(&Resource::onResolvePointer, shared_from_this(), promiseShared, std::placeholders::_1, std::placeholders::_2));
//
return promise1->get_future();
}