key_value_sequence.cpp 2.3 KB

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