Home | Libraries | People | FAQ | More |
Note | |
---|---|
Note that you can find everything that has been included and defined so far here. |
We support addition and subtraction. Let's support multiplication as well.
Note | |
---|---|
Note that you can find everything that has been included and defined so far here. |
We can extend the solution we have built for addition and subtraction.
To do that, we need to add support for multiplication to eval_binary_op
:
> #include <boost/mpl/times.hpp> > template <class L, class R> struct eval_binary_op<L, '*', R> : boost::mpl::times<L, R>::type {};
We had to include <boost/mpl/times.hpp>
to get the boost::mpl::times
metafunction and then we could extend
eval_binary_op
to support
the *
operator as well. We
can try it out:
> eval_binary_op<boost::mpl::int_<3>, '*', boost::mpl::int_<4>>::type mpl_::integral_c<int, 12>
This works as expected. Let's create a token for parsing the *
symbol:
> using times_token = token<lit_c<'*'>>;
Now we can extend our parser to accept the *
symbol as an operator:
> using exp_parser14 = \ ...> build_parser< \ ...> foldl_start_with_parser< \ ...> sequence<one_of<plus_token, minus_token, times_token>, int_token>, \ ...> int_token, \ ...> boost::mpl::quote2<binary_op> \ ...> > \ ...> >;
This version accepts either a +
,
a -
or a *
symbol as the operator. Let's try this out:
> exp_parser14::apply<BOOST_METAPARSE_STRING("2 * 3")>::type mpl_::integral_c<int, 6>
This works as expected. Let's try another, slightly more complicated expression:
> exp_parser14::apply<BOOST_METAPARSE_STRING("1 + 2 * 3")>::type mpl_::integral_c<int, 9>
This returns a wrong result. The value of this expression should be 7
, not 9
.
The problem with this is that our current implementation does not take
operator precedence into account. It treats this expression as (1 +
2) * 3
while
we expect it to be 1 +
(2 * 3)
since addition has higher precedence than multiplication.