| 112 | |
| 113 | template <typename T, typename CompletionToken> |
| 114 | auto async_write_messages(tcp::socket& socket, |
| 115 | const T& message, std::size_t repeat_count, |
| 116 | CompletionToken&& token) |
| 117 | // The return type of the initiating function is deduced from the combination |
| 118 | // of: |
| 119 | // |
| 120 | // - the CompletionToken type, |
| 121 | // - the completion handler signature, and |
| 122 | // - the asynchronous operation's initiation function object. |
| 123 | // |
| 124 | // When the completion token is a simple callback, the return type is always |
| 125 | // void. In this example, when the completion token is boost::asio::yield_context |
| 126 | // (used for stackful coroutines) the return type would also be void, as |
| 127 | // there is no non-error argument to the completion handler. When the |
| 128 | // completion token is boost::asio::use_future it would be std::future<void>. When |
| 129 | // the completion token is boost::asio::deferred, the return type differs for each |
| 130 | // asynchronous operation. |
| 131 | // |
| 132 | // In C++11 we deduce the type from the call to boost::asio::async_compose. |
| 133 | -> decltype( |
| 134 | boost::asio::async_compose< |
| 135 | CompletionToken, void(boost::system::error_code)>( |
| 136 | std::declval<async_write_messages_implementation>(), |
| 137 | token, socket)) |
| 138 | { |
| 139 | // Encode the message and copy it into an allocated buffer. The buffer will |
| 140 | // be maintained for the lifetime of the composed asynchronous operation. |
| 141 | std::ostringstream os; |
| 142 | os << message; |
| 143 | std::unique_ptr<std::string> encoded_message(new std::string(os.str())); |
| 144 | |
| 145 | // Create a steady_timer to be used for the delay between messages. |
| 146 | std::unique_ptr<boost::asio::steady_timer> delay_timer( |
| 147 | new boost::asio::steady_timer(socket.get_executor())); |
| 148 | |
| 149 | // The boost::asio::async_compose function takes: |
| 150 | // |
| 151 | // - our asynchronous operation implementation, |
| 152 | // - the completion token, |
| 153 | // - the completion handler signature, and |
| 154 | // - any I/O objects (or executors) used by the operation |
| 155 | // |
| 156 | // It then wraps our implementation in an intermediate completion handler |
| 157 | // that meets the requirements of a conforming asynchronous operation. This |
| 158 | // includes tracking outstanding work against the I/O executors associated |
| 159 | // with the operation (in this example, this is the socket's executor). |
| 160 | return boost::asio::async_compose< |
| 161 | CompletionToken, void(boost::system::error_code)>( |
| 162 | async_write_messages_implementation{socket, |
| 163 | std::move(encoded_message), repeat_count, |
| 164 | std::move(delay_timer), boost::asio::coroutine()}, |
| 165 | token, socket); |
| 166 | } |
| 167 | |
| 168 | //------------------------------------------------------------------------------ |
| 169 | |