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 main purpose of this example is to show how we can generate output from
7 // a container holding key/value pairs.
8 //
9 // For more information see here: http://spirit.sourceforge.net/home/?p=400
10
11 #include <boost/config/warning_disable.hpp>
12 #include <boost/spirit/include/karma.hpp>
13 #include <boost/spirit/include/karma_stream.hpp>
14 #include <boost/spirit/include/phoenix.hpp>
15 #include <boost/fusion/include/std_pair.hpp>
16
17 #include <iostream>
18 #include <map>
19 #include <algorithm>
20 #include <cstdlib>
21
22 namespace client
23 {
24 namespace karma = boost::spirit::karma;
25
26 typedef std::pair<std::string, boost::optional<std::string> > pair_type;
27
28 template <typename OutputIterator>
29 struct keys_and_values
30 : karma::grammar<OutputIterator, std::vector<pair_type>()>
31 {
keys_and_valuesclient::keys_and_values32 keys_and_values()
33 : keys_and_values::base_type(query)
34 {
35 query = pair << *('&' << pair);
36 pair = karma::string << -('=' << karma::string);
37 }
38
39 karma::rule<OutputIterator, std::vector<pair_type>()> query;
40 karma::rule<OutputIterator, pair_type()> pair;
41 };
42 }
43
44 ///////////////////////////////////////////////////////////////////////////////
main()45 int main()
46 {
47 namespace karma = boost::spirit::karma;
48
49 typedef std::vector<client::pair_type>::value_type value_type;
50 typedef std::back_insert_iterator<std::string> sink_type;
51
52 std::vector<client::pair_type> v;
53 v.push_back(value_type("key1", boost::optional<std::string>("value1")));
54 v.push_back(value_type("key2", boost::optional<std::string>()));
55 v.push_back(value_type("key3", boost::optional<std::string>("")));
56
57 std::string generated;
58 sink_type sink(generated);
59 client::keys_and_values<sink_type> g;
60 if (!karma::generate(sink, g, v))
61 {
62 std::cout << "-------------------------\n";
63 std::cout << "Generating failed\n";
64 std::cout << "-------------------------\n";
65 }
66 else
67 {
68 std::cout << "-------------------------\n";
69 std::cout << "Generated: " << generated << "\n";
70 std::cout << "-------------------------\n";
71 }
72 return 0;
73 }
74
75