attr_vs_actions.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // Copyright (c) 2002-2010 Joel de Guzman
  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. #include <boost/config/warning_disable.hpp>
  6. #include <boost/spirit/include/qi.hpp>
  7. #include <boost/spirit/include/phoenix_core.hpp>
  8. #include <boost/spirit/include/phoenix_operator.hpp>
  9. #include <boost/spirit/include/phoenix_object.hpp>
  10. #include <boost/spirit/include/phoenix_stl.hpp>
  11. #include <boost/fusion/include/adapt_struct.hpp>
  12. #include <boost/fusion/include/io.hpp>
  13. #include <iostream>
  14. #include <string>
  15. #include <complex>
  16. using boost::spirit::qi::grammar;
  17. using boost::spirit::qi::rule;
  18. using boost::spirit::qi::char_;
  19. using boost::spirit::qi::parse;
  20. using boost::spirit::qi::_val;
  21. using boost::spirit::qi::_1;
  22. using boost::phoenix::push_back;
  23. #define ATTR_PROPAGATE
  24. struct test_attr
  25. {
  26. test_attr()
  27. {
  28. std::cout << "default construct" << std::endl;
  29. }
  30. test_attr(char)
  31. {
  32. std::cout << "construct from char" << std::endl;
  33. }
  34. test_attr(test_attr const&)
  35. {
  36. std::cout << "copy construct" << std::endl;
  37. }
  38. test_attr& operator=(test_attr const&)
  39. {
  40. std::cout << "assign" << std::endl;
  41. return *this;
  42. }
  43. };
  44. template <typename Iterator>
  45. struct test_parser : grammar<Iterator, std::vector<test_attr>() >
  46. {
  47. test_parser() : test_parser::base_type(start)
  48. {
  49. #ifdef ATTR_PROPAGATE
  50. start = char_ >> *(',' >> char_);
  51. #else
  52. start = char_[push_back(_val, _1)] >> *(',' >> char_[push_back(_val, _1)]);
  53. #endif
  54. }
  55. rule<Iterator, std::vector<test_attr>()> start;
  56. };
  57. int main()
  58. {
  59. typedef std::string::const_iterator iterator_type;
  60. typedef test_parser<iterator_type> test_parser;
  61. test_parser g;
  62. std::string str = "a,b,c,d,e";
  63. std::vector<test_attr> result;
  64. result.reserve(20);
  65. std::string::const_iterator iter = str.begin();
  66. std::string::const_iterator end = str.end();
  67. bool r = parse(iter, end, g, result);
  68. if (r && iter == end)
  69. {
  70. std::cout << "-------------------------\n";
  71. std::cout << "Parsing succeeded\n";
  72. std::cout << "\n-------------------------\n";
  73. }
  74. else
  75. {
  76. std::cout << "-------------------------\n";
  77. std::cout << "Parsing failed\n";
  78. std::cout << "-------------------------\n";
  79. }
  80. std::cout << "Bye... :-) \n\n";
  81. return 0;
  82. }