]>
Commit | Line | Data |
---|---|---|
7c673cae FG |
1 | [/============================================================================== |
2 | Copyright (C) 2001-2011 Joel de Guzman | |
3 | Copyright (C) 2001-2011 Hartmut Kaiser | |
4 | ||
5 | Distributed under the Boost Software License, Version 1.0. (See accompanying | |
6 | file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) | |
7 | ===============================================================================/] | |
8 | ||
9 | [section Sum - adding numbers] | |
10 | ||
11 | Here's a parser that sums a comma-separated list of numbers. | |
12 | ||
13 | [import ../../example/qi/sum.cpp] | |
14 | ||
15 | Ok we've glossed over some details in our previous examples. First, our | |
16 | includes: | |
17 | ||
18 | [tutorial_adder_includes] | |
19 | ||
20 | Then some using directives: | |
21 | ||
22 | [tutorial_adder_using] | |
23 | ||
24 | [table | |
25 | [[Namespace] [Description]] | |
26 | [[boost::phoenix] [All of phoenix]] | |
27 | [[boost::spirit] [All of spirit]] | |
28 | [[boost::spirit::qi] [All of spirit.qi]] | |
29 | [[boost::spirit::ascii] [ASCII version of `char_` and all char related parsers. Other | |
30 | encodings are also provided (e.g. also an ISO8859.1)]] | |
31 | [[boost::spirit::arg_names] [Special phoenix placeholders for spirit]] | |
32 | ] | |
33 | ||
34 | [note If you feel uneasy with using whole namespaces, feel free to qualify your | |
35 | code, use namespace aliases, etc. For the purpose of this tutorial, we will be | |
36 | presenting unqualified names for both Spirit and __phoenix__. No worries, we | |
37 | will always present the full working code, so you won't get lost. In fact, all | |
38 | examples in this tutorial have a corresponding cpp file that QuickBook (the | |
39 | documentation tool we are using) imports in here as code snippets.] | |
40 | ||
41 | Now the actual parser: | |
42 | ||
43 | [tutorial_adder] | |
44 | ||
45 | The full cpp file for this example can be found here: [@../../example/qi/sum.cpp] | |
46 | ||
47 | This is almost like our original numbers list example. We're incrementally | |
48 | building on top of our examples. This time though, like in the complex number | |
49 | example, we'll be adding the smarts. There's an accumulator (`double& n`) that | |
50 | adds the numbers parsed. On a successful parse, this number is the sum of all | |
51 | the parsed numbers. | |
52 | ||
53 | The first `double_` parser attaches this action: | |
54 | ||
55 | ref(n) = _1 | |
56 | ||
57 | This assigns the parsed result (actually, the attribute of `double_`) to `n`. | |
58 | `ref(n)` tells __phoenix__ that `n` is a mutable reference. `_1` is a | |
59 | __phoenix__ placeholder for the parsed result attribute. | |
60 | ||
61 | The second `double_` parser attaches this action: | |
62 | ||
63 | ref(n) += _1 | |
64 | ||
65 | So, subsequent numbers add into `n`. | |
66 | ||
67 | That wasn't too bad, was it :-) ? | |
68 | ||
69 | [endsect] |