1 [/==============================================================================
2 Copyright (C) 2001-2015 Joel de Guzman
3 Copyright (C) 2001-2011 Hartmut Kaiser
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 ===============================================================================/]
9 [section Sum - adding numbers]
11 Here's a parser that sums a comma-separated list of numbers.
13 Ok we've glossed over some details in our previous examples. First, our
16 #include <boost/spirit/home/x3.hpp>
20 Then some using directives:
22 namespace x3 = boost::spirit::x3;
23 namespace ascii = boost::spirit::x3::ascii;
29 Now the actual parser:
31 template <typename Iterator>
32 bool adder(Iterator first, Iterator last, double& n)
34 auto assign = [&](auto& ctx){ n = _attr(ctx); };
35 auto add = [&](auto& ctx){ n += _attr(ctx); };
37 bool r = x3::phrase_parse(first, last,
41 double_[assign] >> *(',' >> double_[add])
48 if (first != last) // fail if we did not get a full match
53 The full cpp file for this example can be found here: [@../../../example/x3/sum.cpp]
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
61 The first `double_` parser attaches this action:
63 [&](auto& ctx){ n = _attr(ctx); }
65 This assigns the parsed result (actually, the attribute of `double_`) to `n`.
66 The second `double_` parser attaches this action:
68 [&](auto& ctx){ n += _attr(ctx); }
70 So, subsequent numbers add into `n`.
72 That wasn't too bad, was it :-) ?