]> git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/spirit/doc/x3/tutorial/sum_tutorial.qbk
bump version to 12.2.2-pve1
[ceph.git] / ceph / src / boost / libs / spirit / doc / x3 / tutorial / sum_tutorial.qbk
1 [/==============================================================================
2 Copyright (C) 2001-2015 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 Ok we've glossed over some details in our previous examples. First, our
14 includes:
15
16 #include <boost/spirit/home/x3.hpp>
17 #include <iostream>
18 #include <string>
19
20 Then some using directives:
21
22 namespace x3 = boost::spirit::x3;
23 namespace ascii = boost::spirit::x3::ascii;
24
25 using x3::double_;
26 using ascii::space;
27 using x3::_attr;
28
29 Now the actual parser:
30
31 template <typename Iterator>
32 bool adder(Iterator first, Iterator last, double& n)
33 {
34 auto assign = [&](auto& ctx){ n = _attr(ctx); };
35 auto add = [&](auto& ctx){ n += _attr(ctx); };
36
37 bool r = x3::phrase_parse(first, last,
38
39 // Begin grammar
40 (
41 double_[assign] >> *(',' >> double_[add])
42 )
43 ,
44 // End grammar
45
46 space);
47
48 if (first != last) // fail if we did not get a full match
49 return false;
50 return r;
51 }
52
53 The full cpp file for this example can be found here: [@../../../example/x3/sum.cpp]
54
55 This is almost like our original numbers list example. We're incrementally
56 building on top of our examples. This time though, like in the complex number
57 example, we'll be adding the smarts. There's an accumulator (`double& n`) that
58 adds the numbers parsed. On a successful parse, this number is the sum of all
59 the parsed numbers.
60
61 The first `double_` parser attaches this action:
62
63 [&](auto& ctx){ n = _attr(ctx); }
64
65 This assigns the parsed result (actually, the attribute of `double_`) to `n`.
66 The second `double_` parser attaches this action:
67
68 [&](auto& ctx){ n += _attr(ctx); }
69
70 So, subsequent numbers add into `n`.
71
72 That wasn't too bad, was it :-) ?
73
74 [endsect]