Tóm lại, sử dụng std::placeholders::_1
thay vì asio::placeholders:error
.
Asio chỉ hỗ trợ các biến giữ chỗ tiện lợi khi sử dụng Boost.Bind. Các error
placeholder documentation trạng thái:
An argument placeholder, for use with boost::bind()
, ...
Khi sử dụng std::bind()
để tạo ra bộ xử lý, chúng ta cần sử dụng std::bind
's placeholders. Các hoạt động async_accept()
chấp nhận một handler đáp ứng các yêu cầu AcceptHandler loại:
An accept handler must meet the requirements for a handler. A value h
of an accept handler class should work correctly in the expression h(ec)
, where ec
is an lvalue of type const error_code
.
Khi tạo một functor với std::bind()
để hoạt động như một AcceptHandler, nếu muốn để có được những lập luận error_code
, sau đó sử dụng std::placeholders::_1
:
void handle_accept(const std::error_code&);
acceptor.async_accept(server_socket, std::bind(&handle_accept,
std::placeholders::_1 /* error_code */));
Dưới đây là ví dụ tối thiểu hoàn chỉnh demonstrating sử dụng std::bind()
. Lưu ý rằng coliru không xuất hiện để có một phiên bản Asio độc lập có sẵn, nhưng ví dụ là đủ:
#include <iostream>
#include <functional>
#include <boost/asio.hpp>
void handle_accept(const boost::system::error_code& error_code)
{
std::cout << "handle_accept: " << error_code.message() << std::endl;
}
void noop() {}
int main()
{
using boost::asio::ip::tcp;
boost::asio::io_service io_service;
// Create all I/O objects.
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 0));
tcp::socket server_socket(io_service);
tcp::socket client_socket(io_service);
// Connect client and server sockets.
acceptor.async_accept(server_socket, std::bind(&handle_accept,
std::placeholders::_1 /* error_code */));
client_socket.async_connect(acceptor.local_endpoint(), std::bind(&noop));
io_service.run();
}
Output:
handle_accept: Success
Tùy chọn, nếu muốn cho thêm một chút tính cách rườm rà, sau đó đặt tên placeholders có thể được sử dụng:
namespace asio_placeholders
{
auto error = std::placeholders::_1;
}
// ...
acceptor.async_accept(server_socket, std::bind(&handle_accept,
asio_placeholders::error));
loại unspecified
quan sát i n mã nguồn chỉ được sử dụng khi tạo tài liệu, như trong code này:
#if defined(GENERATING_DOCUMENTATION)
/// An argument placeholder, for use with boost::bind(), that corresponds to
/// the error argument of a handler for any of the asynchronous functions.
unspecified error;
// ...
#elseif
Ngoài ra khi sử dụng Boost.Bind với phi tăng Asio bạn phải xác định 'ASIO_HAS_BOOST_BIND' để có được giữ chỗ thuận tiện. – robsn