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 Complex - Our first complex parser]
11 Well, not really a complex parser, but a parser that parses complex numbers.
13 Here's a simple parser expression for complex numbers:
15 '(' >> double_ >> -(',' >> double_) >> ')'
18 What's new? Well, we have:
20 # Alternates: e.g. `a | b`. Try `a` first. If it succeeds, good. If not, try the
21 next alternative, `b`.
22 # Optionals: e.g. -p. Match the parser p zero or one time.
24 The complex parser presented above reads as:
26 * One or two real numbers in parentheses, separated by comma (the second number is optional)
27 * *OR* a single real number.
29 This parser can parse complex numbers of the form:
35 Here goes, this time with actions:
39 template <typename Iterator>
40 bool parse_complex(Iterator first, Iterator last, std::complex<double>& c)
42 using boost::spirit::x3::double_;
43 using boost::spirit::x3::_attr;
44 using boost::spirit::x3::phrase_parse;
45 using boost::spirit::x3::ascii::space;
49 auto fr = [&](auto& ctx){ rN = _attr(ctx); };
50 auto fi = [&](auto& ctx){ iN = _attr(ctx); };
52 bool r = phrase_parse(first, last,
57 >> -(',' >> double_[fi]) >> ')'
64 if (!r || first != last) // fail if we did not get a full match
66 c = std::complex<double>(rN, iN);
71 The full cpp file for this example can be found here: [@../../../example/x3/complex_number.cpp]
73 The `double_` parser attaches this action:
75 [&](auto& ctx){ n = _attr(ctx); }
77 This assigns the parsed result (actually, the attribute of `double_`) to n.