Oh, but
tcp::endpoint remote_endpoint = *resolver.resolve(query);
与迭代器打交道非常多!它使用它来取消引用。注意到那个可爱的星星了吗?这是指针间接操作员。
至于你的电话:
resolver.async_resolve(query,
[this](const tcp::endpoint srvEndpoint, std::error_code error)
{
IOService->post(
[this, error, srvEndpoint]
{
handle_resolve_handler(error, srvEndpoint);
});
});
That does not satisfy the completion handler requirements. Indeed, trying to compile it with Boost Asio² gives a slew of errors: Live On Coliru:
main.cpp:12:14: required from here
/usr/local/include/boost/asio/ip/basic_resolver.hpp:163:5: error: static assertion failed: ResolveHandler type requirements not met
BOOST_ASIO_RESOLVE_HANDLER_CHECK(
^
/usr/local/include/boost/asio/ip/basic_resolver.hpp:163:5: error: no match for call to '(Demo::doResolve()::<lambda(boost::asio::ip::tcp::endpoint, boost::system::error_code)>) (const boost::system::error_code&, const boost::asio::ip::basic_resolver_iterator<boost::asio::ip::tcp>&)'
BOOST_ASIO_RESOLVE_HANDLER_CHECK(
文档说:
![enter image description here](https://i.stack.imgur.com/YsUA8.png)
你瞧,你的迭代器又出现了!这绝非偶然。该库的设计是这样的,无论选择什么接口,异步调用都将始终返回相同的数据。
Cobbling it together: Live On Coliru
#include <boost/asio.hpp>
#include <iostream>
namespace asio = boost::asio;
using boost::system::error_code;
using asio::ip::tcp;
struct Demo {
Demo(asio::io_service& svc) : _svc(svc) {}
void doResolve() {
resolver.async_resolve(query, [this](error_code error, tcp::resolver::iterator it) {
tcp::endpoint ep = error? tcp::endpoint{} : *it;
_svc.post([this, error, ep] { handle_resolve_handler(error, ep); });
});
}
private:
asio::io_service& _svc;
tcp::resolver resolver {_svc};
tcp::resolver::query query {"www.google.com", "https"};
void handle_resolve_handler(error_code ec, tcp::endpoint srvEndpoint) {
std::cout << "handle_resolve_handler: " << ec.message() << " " << srvEndpoint << "\n";
}
};
int main() {
asio::io_service svc;
Demo x(svc);
x.doResolve();
svc.run();
}
Prints³:
handle_resolve_handler: Success 216.58.213.196:443
1 参见使用协程时的区别(yield
or yield[ec]
), asio::use_future
etc.: 如何将 error_code 设置为 asio::yield_context
² 基本上s/boost::system::error_code/std::error_code/
³ 在具有网络访问权限的系统上