sum_tutorial.qbk 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 Sum - adding numbers]
  8. Here's a parser that sums a comma-separated list of numbers.
  9. Ok we've glossed over some details in our previous examples. First, our
  10. includes:
  11. #include <boost/spirit/home/x3.hpp>
  12. #include <iostream>
  13. #include <string>
  14. Then some using directives:
  15. namespace x3 = boost::spirit::x3;
  16. namespace ascii = boost::spirit::x3::ascii;
  17. using x3::double_;
  18. using ascii::space;
  19. using x3::_attr;
  20. Now the actual parser:
  21. template <typename Iterator>
  22. bool adder(Iterator first, Iterator last, double& n)
  23. {
  24. auto assign = [&](auto& ctx){ n = _attr(ctx); };
  25. auto add = [&](auto& ctx){ n += _attr(ctx); };
  26. bool r = x3::phrase_parse(first, last,
  27. // Begin grammar
  28. (
  29. double_[assign] >> *(',' >> double_[add])
  30. )
  31. ,
  32. // End grammar
  33. space);
  34. if (first != last) // fail if we did not get a full match
  35. return false;
  36. return r;
  37. }
  38. The full cpp file for this example can be found here:
  39. [@../../../example/x3/sum.cpp sum.cpp]
  40. This is almost like our original numbers list example. We're incrementally
  41. building on top of our examples. This time though, like in the complex number
  42. example, we'll be adding the smarts. There's an accumulator (`double& n`) that
  43. adds the numbers parsed. On a successful parse, this number is the sum of all
  44. the parsed numbers.
  45. The first `double_` parser attaches this action:
  46. [&](auto& ctx){ n = _attr(ctx); }
  47. This assigns the parsed result (actually, the attribute of `double_`) to `n`.
  48. The second `double_` parser attaches this action:
  49. [&](auto& ctx){ n += _attr(ctx); }
  50. So, subsequent numbers add into `n`.
  51. That wasn't too bad, was it :-) ?
  52. [endsect]