2016-10-17 1 views
0

私は入力を提供するためにクラス内のシフト演算子をオーバーロードしました。私はその方法で同期asio::write()を行い、その後すぐに非同期asio::async_read()をします。私の問題は、シフトオーバーロードが自分のクラスの友人である必要があるということです。friendメソッドからのasync_readの使用

私はasync_readするためにこれを供給した場合:

void operator>>(const vector<unsigned char> input, Socket &socket) { 
     const size_t size = input.size(); 
     const size_t bytes = asio::write(socket.connection_socket, asio::buffer(input, size)); 
     if (bytes != size) { 
     const std::error_code ec; 
     throw std::system_error(ec, fmt::format("Tried to send {0} bytes but sent {1} instead.", size, bytes)); 
     } 
     asio::async_read(socket.connection_socket, 
         asio::buffer(socket.read_buffer), 
         std::bind(&Socket::handle_async_read, 
           this, 
           std::placeholders::_1)); 
    } 

を私はエラーを取得:

error: invalid use of 'this' outside of a non-static member function 

私はソケットへの参照を渡した場合:

void operator>>(const vector<unsigned char> input, Socket &socket) { 
     const size_t size = input.size(); 
     const size_t bytes = asio::write(socket.connection_socket, asio::buffer(input, size)); 
     if (bytes != size) { 
     const std::error_code ec; 
     throw std::system_error(ec, fmt::format("Tried to send {0} bytes but sent {1} instead.", size, bytes)); 
     } 
     asio::async_read(socket.connection_socket, 
         asio::buffer(socket.read_buffer), 
         std::bind(&Socket::handle_async_read, 
           socket, 
           std::placeholders::_1)); 
    } 

を私はエラーを取得します:

error: call to implicitly-deleted copy constructor of 'std::__1::__bind<void 
     (databaseclient::internal::Socket::*)(std::__1::error_code &, unsigned long), databaseclient::internal::Socket &, std::__1::placeholders::__ph<1> &>' 
    ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; 
    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 

答えて

2

あなたはソケットのコピーにバインドしていますが、これは不正です。

これが優れている:(バインドは時代錯誤であるので)

asio::async_read(socket.connection_socket, 
         asio::buffer(socket.read_buffer), 
         std::bind(&Socket::handle_async_read, 
           std::ref(socket), 
           std::placeholders::_1)); 

これはさらに良いです:

asio::async_read(socket.connection_socket, 
         asio::buffer(socket.read_buffer), 
         [&socket](auto const& ec, auto transferred) 
         { 
         handle_async_read(socket, ec); 
         }); 
関連する問題