#include <iostream>
#include <boost/mpl/int.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/mpl/min_max.hpp>
#include <boost/proto/core.hpp>
#include <boost/proto/context.hpp>
#include <boost/proto/transform.hpp>
namespace mpl = boost::mpl;
namespace proto = boost::proto;
using proto::_;
template<typename I> struct placeholder : I {};
struct CalculatorGrammar
: proto::or_<
proto::when< proto::terminal< placeholder<_> >, proto::_value >
, proto::when< proto::terminal<_>, mpl::int_<0>() >
, proto::when< proto::nary_expr<_, proto::vararg<_> >
, proto::fold<_, mpl::int_<0>(), mpl::max<CalculatorGrammar, proto::_state>() > >
>
{};
template<typename Expr>
struct calculator_arity
: boost::result_of<CalculatorGrammar(Expr)>
{};
template<typename Expr>
struct calculator_expression;
struct calculator_domain
: proto::domain<proto::generator<calculator_expression> >
{};
struct calculator_context
: proto::callable_context< calculator_context const >
{
double d[2];
typedef double result_type;
explicit calculator_context(double d1 = 0., double d2 = 0.)
{
d[0] = d1;
d[1] = d2;
}
template<typename I>
double operator ()(proto::tag::terminal, placeholder<I>) const
{
return d[ I() - 1 ];
}
};
template<typename Expr>
struct calculator_expression
: proto::extends<Expr, calculator_expression<Expr>, calculator_domain>
{
typedef
proto::extends<Expr, calculator_expression<Expr>, calculator_domain>
base_type;
explicit calculator_expression(Expr const &expr = Expr())
: base_type(expr)
{}
BOOST_PROTO_EXTENDS_USING_ASSIGN(calculator_expression<Expr>)
double operator ()() const
{
BOOST_MPL_ASSERT_RELATION(0, ==, calculator_arity<Expr>::type::value);
calculator_context const ctx;
return proto::eval(*this, ctx);
}
double operator ()(double d1) const
{
BOOST_MPL_ASSERT_RELATION(1, ==, calculator_arity<Expr>::type::value);
calculator_context const ctx(d1);
return proto::eval(*this, ctx);
}
double operator ()(double d1, double d2) const
{
BOOST_MPL_ASSERT_RELATION(2, ==, calculator_arity<Expr>::type::value);
calculator_context const ctx(d1, d2);
return proto::eval(*this, ctx);
}
};
calculator_expression<proto::terminal< placeholder< mpl::int_<1> > >::type> const _1;
calculator_expression<proto::terminal< placeholder< mpl::int_<2> > >::type> const _2;
int main()
{
std::cout << (_1 + 2.0)( 3.0 ) << std::endl;
std::cout << ( _1 * _2 )( 3.0, 2.0 ) << std::endl;
std::cout << ( (_1 - _2) / _2 )( 3.0, 2.0 ) << std::endl;
return 0;
}