Boost C++ Libraries Home Libraries People FAQ More

PrevUpHomeNext

6. Adding support for other operators

[Note] Note

Note that you can find everything that has been included and defined so far here.

Our parsers now support expressions adding numbers together. In this section we will add support for the - operator, so expressions like 1 + 2 - 3 can be evaluated.

[Note] Note

Note that you can find everything that has been included and defined so far here.

Currently we use the plus_token for parsing "the" operator, which has to be +. We can define a new token for parsing the - symbol:

> using minus_token = token<lit_c<'-'>>;

We need to build a parser that accepts either a + or a - symbol. This can be implemented using one_of:

> #include <boost/metaparse/one_of.hpp>

one_of<plus_token, minus_token> is a parser which accepts either a + (using plus_token) or a - (using minus_token) symbol. The result of parsing is the result of the parser that succeeded.

[Note] Note

You can give any parser to one_of, therefore it is possible that more than one of them can parse the input. In those cases the order matters: one_of tries parsing the input with the parsers from left to right and the first one that succeeds, wins.

Using this, we can make our parser accept subtractions as well:

> using exp_parser12 = \
...> build_parser< \
...>   foldl_start_with_parser< \
...>     sequence<one_of<plus_token, minus_token>, int_token>, \
...>     int_token, \
...>     boost::mpl::quote2<sum_items> \
...>   > \
...> >;

copy-paste friendly version

It uses one_of<plus_token, minus_token> as the separator for the numbers. Let's try it out:

> exp_parser12::apply<BOOST_METAPARSE_STRING("1 + 2 - 3")>::type
mpl_::integral_c<int, 6>

The result is not correct. The reason for this is that sum_items, the function we summarise with ignores which operator was used and assumes that it is always +.


PrevUpHomeNext