| 1 | |
| 2 | // Copyright Nat Goodspeed 2013. |
| 3 | // Distributed under the Boost Software License, Version 1.0. |
| 4 | // (See accompanying file LICENSE_1_0.txt or copy at |
| 5 | // http://www.boost.org/LICENSE_1_0.txt) |
| 6 | |
| 7 | #include <boost/coroutine/all.hpp> |
| 8 | |
| 9 | #include <iostream> |
| 10 | #include <iomanip> |
| 11 | #include <vector> |
| 12 | #include <string> |
| 13 | #include <utility> |
| 14 | |
| 15 | #include <boost/assign/list_of.hpp> |
| 16 | #include <boost/bind.hpp> |
| 17 | #include <boost/range.hpp> |
| 18 | |
| 19 | struct FinalEOL |
| 20 | { |
| 21 | ~FinalEOL() { std::cout << std::endl; } |
| 22 | }; |
| 23 | |
| 24 | void layout(boost::coroutines::asymmetric_coroutine<std::string>::pull_type& in, int num, int width) |
| 25 | { |
| 26 | // Finish the last line when we leave by whatever means |
| 27 | FinalEOL eol; |
| 28 | |
| 29 | // Pull values from upstream, lay them out 'num' to a line |
| 30 | for (;;) |
| 31 | { |
| 32 | for (int i = 0; i < num; ++i) |
| 33 | { |
| 34 | // when we exhaust the input, stop |
| 35 | if (! in) |
| 36 | return; |
| 37 | |
| 38 | std::cout << std::setw(width) << in.get(); |
| 39 | // now that we've handled this item, advance to next |
| 40 | in(); |
| 41 | } |
| 42 | // after 'num' items, line break |
| 43 | std::cout << std::endl; |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | int main(int argc, char *argv[]) |
| 48 | { |
| 49 | std::vector<std::string> words = boost::assign::list_of |
| 50 | (t: "peas" ) |
| 51 | ("porridge" ) |
| 52 | ("hot" ) |
| 53 | ("peas" ) |
| 54 | ("porridge" ) |
| 55 | ("cold" ) |
| 56 | ("peas" ) |
| 57 | ("porridge" ) |
| 58 | ("in" ) |
| 59 | ("the" ) |
| 60 | ("pot" ) |
| 61 | ("nine" ) |
| 62 | ("days" ) |
| 63 | ("old" ) |
| 64 | ; |
| 65 | |
| 66 | boost::coroutines::asymmetric_coroutine<std::string>::push_type writer( |
| 67 | boost::bind(f: layout, a1: _1, a2: 5, a3: 15)); |
| 68 | |
| 69 | std::copy(first: boost::begin(r&: words), last: boost::end(r&: words), result: boost::begin(r&: writer)); |
| 70 | |
| 71 | std::cout << "\nDone" << std::endl; |
| 72 | |
| 73 | return EXIT_SUCCESS; |
| 74 | } |
| 75 | |