num_list4.qbk 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. [/==============================================================================
  2. Copyright (C) 2001-2015 Joel de Guzman
  3. Copyright (C) 2001-2011 Hartmut Kaiser
  4. Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. ===============================================================================/]
  7. [section Number List Attribute - one more, with style]
  8. You've seen that the `double_` parser has a `double` attribute. All parsers have
  9. an attribute, even complex parsers. Those that are composed from primitives
  10. using operators, like the list parser, also have an attribute. It so happens that
  11. the attribute of a list parser:
  12. p % d
  13. is a `std::vector` of the attribute of `p`. So, for our parser:
  14. double_ % ','
  15. we'll have an attribute of:
  16. std::vector<double>
  17. So, what does this give us? Well, we can simply pass in a `std::vector<double>`
  18. to our number list parser and it will happily churn out our result in our
  19. vector. For that to happen, we'll use a variation of the `phrase_parse` with
  20. an additional argument: the parser's attribute. With the following arguments
  21. passed to `phrase_parse`
  22. # An iterator pointing to the start of the input
  23. # An iterator pointing to one past the end of the input
  24. # The parser object
  25. # Another parser called the skip parser
  26. # The parser's attribute
  27. Our parser now is further simplified to:
  28. template <typename Iterator>
  29. bool parse_numbers(Iterator first, Iterator last, std::vector<double>& v)
  30. {
  31. using x3::double_;
  32. using x3::phrase_parse;
  33. using x3::_attr;
  34. using ascii::space;
  35. bool r = phrase_parse(first, last,
  36. // Begin grammar
  37. (
  38. double_ % ','
  39. )
  40. ,
  41. // End grammar
  42. space, v);
  43. if (first != last) // fail if we did not get a full match
  44. return false;
  45. return r;
  46. }
  47. The full cpp file for this example can be found here:
  48. [@../../../example/x3/num_list/num_list4.cpp num_list4.cpp]
  49. [*Hey, no more actions!!!] Now we're entering the realm of attribute grammars.
  50. Cool eh?
  51. [endsect]