• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <boost/config/warning_disable.hpp>
11 
12 #include <string>
13 #include <vector>
14 
15 #include <boost/spirit/include/karma.hpp>
16 #include <boost/spirit/include/phoenix_stl.hpp>
17 
18 namespace client
19 {
20     namespace karma = boost::spirit::karma;
21     namespace phx = boost::phoenix;
22 
23     template <typename OutputIterator>
24     struct quoted_strings
25       : karma::grammar<OutputIterator, std::vector<std::string>()>
26     {
quoted_stringsclient::quoted_strings27         quoted_strings()
28           : quoted_strings::base_type(strings)
29         {
30             strings = (bareword | qstring) % ' ';
31             bareword = karma::repeat(phx::size(karma::_val))
32                           [ karma::alnum | karma::char_("-.,_$") ];
33             qstring = '"' << karma::string << '"';
34         }
35 
36         karma::rule<OutputIterator, std::vector<std::string>()> strings;
37         karma::rule<OutputIterator, std::string()> bareword, qstring;
38     };
39 }
40 
main()41 int main()
42 {
43     namespace karma = boost::spirit::karma;
44 
45     typedef std::back_insert_iterator<std::string> sink_type;
46 
47     std::string generated;
48     sink_type sink(generated);
49 
50     std::vector<std::string> v;
51     v.push_back("foo");
52     v.push_back("bar baz");
53     v.push_back("hello");
54 
55     client::quoted_strings<sink_type> g;
56     if (!karma::generate(sink, g, v))
57     {
58         std::cout << "-------------------------\n";
59         std::cout << "Generating failed\n";
60         std::cout << "-------------------------\n";
61     }
62     else
63     {
64         std::cout << "-------------------------\n";
65         std::cout << "Generated: " << generated << "\n";
66         std::cout << "-------------------------\n";
67     }
68     return 0;
69 }
70 
71