| 141 | |
| 142 | template <typename T, typename CompletionToken> |
| 143 | auto async_write_message(tcp::socket& socket, |
| 144 | const T& message, CompletionToken&& token) |
| 145 | // The return type of the initiating function is deduced from the combination |
| 146 | // of: |
| 147 | // |
| 148 | // - the CompletionToken type, |
| 149 | // - the completion handler signature, and |
| 150 | // - the asynchronous operation's initiation function object. |
| 151 | // |
| 152 | // When the completion token is a simple callback, the return type is always |
| 153 | // void. In this example, when the completion token is boost::asio::yield_context |
| 154 | // (used for stackful coroutines) the return type would also be void, as |
| 155 | // there is no non-error argument to the completion handler. When the |
| 156 | // completion token is boost::asio::use_future it would be std::future<void>. When |
| 157 | // the completion token is boost::asio::deferred, the return type differs for each |
| 158 | // asynchronous operation. |
| 159 | // |
| 160 | // In C++11 we deduce the type from the call to boost::asio::async_initiate. |
| 161 | -> decltype( |
| 162 | boost::asio::async_initiate< |
| 163 | CompletionToken, void(boost::system::error_code)>( |
| 164 | async_write_message_initiation(), token, |
| 165 | std::ref(socket), std::declval<std::unique_ptr<std::string>>())) |
| 166 | { |
| 167 | // Encode the message and copy it into an allocated buffer. The buffer will |
| 168 | // be maintained for the lifetime of the asynchronous operation. |
| 169 | std::ostringstream os; |
| 170 | os << message; |
| 171 | std::unique_ptr<std::string> encoded_message(new std::string(os.str())); |
| 172 | |
| 173 | // The boost::asio::async_initiate function takes: |
| 174 | // |
| 175 | // - our initiation function object, |
| 176 | // - the completion token, |
| 177 | // - the completion handler signature, and |
| 178 | // - any additional arguments we need to initiate the operation. |
| 179 | // |
| 180 | // It then asks the completion token to create a completion handler (i.e. a |
| 181 | // callback) with the specified signature, and invoke the initiation function |
| 182 | // object with this completion handler as well as the additional arguments. |
| 183 | // The return value of async_initiate is the result of our operation's |
| 184 | // initiating function. |
| 185 | // |
| 186 | // Note that we wrap non-const reference arguments in std::reference_wrapper |
| 187 | // to prevent incorrect decay-copies of these objects. |
| 188 | return boost::asio::async_initiate< |
| 189 | CompletionToken, void(boost::system::error_code)>( |
| 190 | async_write_message_initiation(), token, |
| 191 | std::ref(socket), std::move(encoded_message)); |
| 192 | } |
| 193 | |
| 194 | //------------------------------------------------------------------------------ |
| 195 | |