quoted_strings.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 purpose of this example is to demonstrate how to utilize alternatives
  6. // and the built in matching capabilities of Karma generators to emit output
  7. // in different formats based on the content of an attribute (not its type).
  8. #include <boost/config/warning_disable.hpp>
  9. #include <string>
  10. #include <vector>
  11. #include <boost/spirit/include/karma.hpp>
  12. #include <boost/spirit/include/phoenix_stl.hpp>
  13. namespace client
  14. {
  15. namespace karma = boost::spirit::karma;
  16. namespace phx = boost::phoenix;
  17. template <typename OutputIterator>
  18. struct quoted_strings
  19. : karma::grammar<OutputIterator, std::vector<std::string>()>
  20. {
  21. quoted_strings()
  22. : quoted_strings::base_type(strings)
  23. {
  24. strings = (bareword | qstring) % ' ';
  25. bareword = karma::repeat(phx::size(karma::_val))
  26. [ karma::alnum | karma::char_("-.,_$") ];
  27. qstring = '"' << karma::string << '"';
  28. }
  29. karma::rule<OutputIterator, std::vector<std::string>()> strings;
  30. karma::rule<OutputIterator, std::string()> bareword, qstring;
  31. };
  32. }
  33. int main()
  34. {
  35. namespace karma = boost::spirit::karma;
  36. typedef std::back_insert_iterator<std::string> sink_type;
  37. std::string generated;
  38. sink_type sink(generated);
  39. std::vector<std::string> v;
  40. v.push_back("foo");
  41. v.push_back("bar baz");
  42. v.push_back("hello");
  43. client::quoted_strings<sink_type> g;
  44. if (!karma::generate(sink, g, v))
  45. {
  46. std::cout << "-------------------------\n";
  47. std::cout << "Generating failed\n";
  48. std::cout << "-------------------------\n";
  49. }
  50. else
  51. {
  52. std::cout << "-------------------------\n";
  53. std::cout << "Generated: " << generated << "\n";
  54. std::cout << "-------------------------\n";
  55. }
  56. return 0;
  57. }