Created
February 3, 2012 17:24
-
-
Save K240-zz/1731263 to your computer and use it in GitHub Desktop.
Simple Expression using boost::spirit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <cmath> | |
| #include <iostream> | |
| #include <string> | |
| #include <vector> | |
| #include <boost/fusion/tuple.hpp> | |
| #include <boost/spirit/include/qi.hpp> | |
| #include <boost/spirit/include/phoenix.hpp> | |
| using namespace std; | |
| using namespace boost; | |
| using namespace boost::spirit; | |
| struct sin_expr | |
| { | |
| template <typename T> | |
| struct result { typedef T type; }; | |
| double operator()(double const& expr) const | |
| { | |
| return double(::sin(expr)); | |
| } | |
| }; | |
| struct cos_expr | |
| { | |
| template <typename T> | |
| struct result { typedef T type; }; | |
| double operator()(double const& expr) const | |
| { | |
| return double(::cos(expr)); | |
| } | |
| }; | |
| boost::phoenix::function<sin_expr> Sin; | |
| boost::phoenix::function<cos_expr> Cos; | |
| template<typename Iterator> | |
| struct calc : qi::grammar<Iterator, double(), ascii::space_type> | |
| { | |
| qi::rule<Iterator, double(), ascii::space_type> expr, term, fctr; | |
| calc() : calc::base_type(expr) | |
| { | |
| expr = term[_val = _1] >> *( ('+' >> term[_val += _1]) | |
| | ('-' >> term[_val -= _1]) ); | |
| term = fctr[_val = _1] >> *( ('*' >> fctr[_val *= _1]) | |
| | ('/' >> fctr[_val /= _1]) ); | |
| fctr = double_[_val = _1] | |
| | '(' >> expr[_val = _1] >> ')' | |
| | ( '-' >> fctr[_val = -_1]) | |
| | ( '+' >> fctr[_val = _1]) | |
| | lit("sin") >> '(' >> expr[_val = Sin(_1)] >> ')' | |
| | lit("cos") >> '(' >> expr[_val = Cos(_1)] >> ')' | |
| ; | |
| } | |
| }; | |
| double do_expression(string value) | |
| { | |
| calc<string::iterator> c; | |
| double result = std::numeric_limits<double>::signaling_NaN(); | |
| string::iterator it = value.begin(); | |
| qi::phrase_parse(it, value.end(), c, ascii::space, result); | |
| return result; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment