| 1 | // Copyright (c) 2001-2010 Hartmut Kaiser |
|---|---|
| 2 | // |
| 3 | // Distributed under the Boost Software License, Version 1.0. (See accompanying |
| 4 | // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) |
| 5 | |
| 6 | // The purpose of this example is to demonstrate how to utilize alternatives |
| 7 | // and the built in matching capabilities of Karma generators to emit output |
| 8 | // in different formats based on the content of an attribute (not its type). |
| 9 | |
| 10 | #include <string> |
| 11 | #include <vector> |
| 12 | |
| 13 | #include <boost/spirit/include/karma.hpp> |
| 14 | #include <boost/phoenix/stl.hpp> |
| 15 | |
| 16 | namespace client |
| 17 | { |
| 18 | namespace karma = boost::spirit::karma; |
| 19 | namespace phx = boost::phoenix; |
| 20 | |
| 21 | template <typename OutputIterator> |
| 22 | struct quoted_strings |
| 23 | : karma::grammar<OutputIterator, std::vector<std::string>()> |
| 24 | { |
| 25 | quoted_strings() |
| 26 | : quoted_strings::base_type(strings) |
| 27 | { |
| 28 | strings = (bareword | qstring) % ' '; |
| 29 | bareword = karma::repeat(phx::size(a0: karma::_val)) |
| 30 | [ karma::alnum | karma::char_("-.,_$") ]; |
| 31 | qstring = '"' << karma::string << '"'; |
| 32 | } |
| 33 | |
| 34 | karma::rule<OutputIterator, std::vector<std::string>()> strings; |
| 35 | karma::rule<OutputIterator, std::string()> bareword, qstring; |
| 36 | }; |
| 37 | } |
| 38 | |
| 39 | int main() |
| 40 | { |
| 41 | namespace karma = boost::spirit::karma; |
| 42 | |
| 43 | typedef std::back_insert_iterator<std::string> sink_type; |
| 44 | |
| 45 | std::string generated; |
| 46 | sink_type sink(generated); |
| 47 | |
| 48 | std::vector<std::string> v; |
| 49 | v.push_back(x: "foo"); |
| 50 | v.push_back(x: "bar baz"); |
| 51 | v.push_back(x: "hello"); |
| 52 | |
| 53 | client::quoted_strings<sink_type> g; |
| 54 | if (!karma::generate(sink_&: sink, expr: g, attr: v)) |
| 55 | { |
| 56 | std::cout << "-------------------------\n"; |
| 57 | std::cout << "Generating failed\n"; |
| 58 | std::cout << "-------------------------\n"; |
| 59 | } |
| 60 | else |
| 61 | { |
| 62 | std::cout << "-------------------------\n"; |
| 63 | std::cout << "Generated: "<< generated << "\n"; |
| 64 | std::cout << "-------------------------\n"; |
| 65 | } |
| 66 | return 0; |
| 67 | } |
| 68 | |
| 69 |
