#include #include #include #include #include #include #include struct add_func; struct sub_func; template class binary_op; typedef boost::variant >, boost::recursive_wrapper > > expr_t; template class binary_op { public: // Constructor binary_op(const expr_t &l, const expr_t &r) : left(l), right(r) { } expr_t left; expr_t right; }; class evaluator : public boost::static_visitor { public: double operator()(double val) const { return val; } double operator()(const binary_op &f) const { return boost::apply_visitor(*this, f.left)+ boost::apply_visitor(*this, f.right); } double operator()(const binary_op &f) const { return boost::apply_visitor(*this, f.left)- boost::apply_visitor(*this, f.right); } }; // Generate a random double static double frand() { long int lrand=random(); return ((double)lrand); } // Used to recursively form a parse tree. At each level, the left branch // continues on, while the right one terminates in a leaf. static expr_t get_expr(size_t depth, size_t maxdepth) { if (depth>maxdepth) { return frand(); } return binary_op(get_expr(depth+1, maxdepth), frand()); } static void dotest() { expr_t result(get_expr(0, 10000)); double val=boost::apply_visitor(evaluator(), result); printf("Resulting value: %f\n", val); } int main(void) { dotest(); return 0; }