]>
Commit | Line | Data |
---|---|---|
7c673cae FG |
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 | ||
7c673cae FG |
11 | #include <boost/spirit/include/karma.hpp> |
12 | #include <boost/spirit/include/karma_stream.hpp> | |
1e59de90 | 13 | #include <boost/phoenix.hpp> |
7c673cae FG |
14 | #include <boost/fusion/include/std_pair.hpp> |
15 | ||
16 | #include <iostream> | |
17 | #include <map> | |
18 | #include <algorithm> | |
19 | #include <cstdlib> | |
20 | ||
21 | namespace client | |
22 | { | |
23 | namespace karma = boost::spirit::karma; | |
24 | ||
25 | typedef std::pair<std::string, boost::optional<std::string> > pair_type; | |
26 | ||
27 | template <typename OutputIterator> | |
28 | struct keys_and_values | |
29 | : karma::grammar<OutputIterator, std::vector<pair_type>()> | |
30 | { | |
31 | keys_and_values() | |
32 | : keys_and_values::base_type(query) | |
33 | { | |
34 | query = pair << *('&' << pair); | |
35 | pair = karma::string << -('=' << karma::string); | |
36 | } | |
37 | ||
38 | karma::rule<OutputIterator, std::vector<pair_type>()> query; | |
39 | karma::rule<OutputIterator, pair_type()> pair; | |
40 | }; | |
41 | } | |
42 | ||
43 | /////////////////////////////////////////////////////////////////////////////// | |
44 | int main() | |
45 | { | |
46 | namespace karma = boost::spirit::karma; | |
47 | ||
48 | typedef std::vector<client::pair_type>::value_type value_type; | |
49 | typedef std::back_insert_iterator<std::string> sink_type; | |
50 | ||
51 | std::vector<client::pair_type> v; | |
52 | v.push_back(value_type("key1", boost::optional<std::string>("value1"))); | |
53 | v.push_back(value_type("key2", boost::optional<std::string>())); | |
54 | v.push_back(value_type("key3", boost::optional<std::string>(""))); | |
55 | ||
56 | std::string generated; | |
57 | sink_type sink(generated); | |
58 | client::keys_and_values<sink_type> g; | |
59 | if (!karma::generate(sink, g, v)) | |
60 | { | |
61 | std::cout << "-------------------------\n"; | |
62 | std::cout << "Generating failed\n"; | |
63 | std::cout << "-------------------------\n"; | |
64 | } | |
65 | else | |
66 | { | |
67 | std::cout << "-------------------------\n"; | |
68 | std::cout << "Generated: " << generated << "\n"; | |
69 | std::cout << "-------------------------\n"; | |
70 | } | |
71 | return 0; | |
72 | } | |
73 |