sum_tutorial.qbk 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. [/==============================================================================
  2. Copyright (C) 2001-2011 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. [import ../../example/qi/sum.cpp]
  10. Ok we've glossed over some details in our previous examples. First, our
  11. includes:
  12. [tutorial_adder_includes]
  13. Then some using directives:
  14. [tutorial_adder_using]
  15. [table
  16. [[Namespace] [Description]]
  17. [[boost::phoenix] [All of phoenix]]
  18. [[boost::spirit] [All of spirit]]
  19. [[boost::spirit::qi] [All of spirit.qi]]
  20. [[boost::spirit::ascii] [ASCII version of `char_` and all char related parsers. Other
  21. encodings are also provided (e.g. also an ISO8859.1)]]
  22. [[boost::spirit::arg_names] [Special phoenix placeholders for spirit]]
  23. ]
  24. [note If you feel uneasy with using whole namespaces, feel free to qualify your
  25. code, use namespace aliases, etc. For the purpose of this tutorial, we will be
  26. presenting unqualified names for both Spirit and __phoenix__. No worries, we
  27. will always present the full working code, so you won't get lost. In fact, all
  28. examples in this tutorial have a corresponding cpp file that QuickBook (the
  29. documentation tool we are using) imports in here as code snippets.]
  30. Now the actual parser:
  31. [tutorial_adder]
  32. The full cpp file for this example can be found here: [@../../example/qi/sum.cpp]
  33. This is almost like our original numbers list example. We're incrementally
  34. building on top of our examples. This time though, like in the complex number
  35. example, we'll be adding the smarts. There's an accumulator (`double& n`) that
  36. adds the numbers parsed. On a successful parse, this number is the sum of all
  37. the parsed numbers.
  38. The first `double_` parser attaches this action:
  39. ref(n) = _1
  40. This assigns the parsed result (actually, the attribute of `double_`) to `n`.
  41. `ref(n)` tells __phoenix__ that `n` is a mutable reference. `_1` is a
  42. __phoenix__ placeholder for the parsed result attribute.
  43. The second `double_` parser attaches this action:
  44. ref(n) += _1
  45. So, subsequent numbers add into `n`.
  46. That wasn't too bad, was it :-) ?
  47. [endsect]