摘录自http://www.cpp-prog.com/2009/0121/55_4.html 使用Spirit中的绝大部分都不需要编译,包括下面这个代码,只要包含头文件即可。 #include <iostream> #include <vector> #include <boost/spirit.hpp> #include <boost/spirit/phoenix.hpp> using namespace std; using namespace boost::spirit; using namespace phoenix; int main() { //为rule准备一个val变量,类型为double //准确地说:是一个phoenix类(这里的member1),它和其它phoenix类组成lambda表达式,在lambda中可以把它看成是一个double。 struct calc_closure : boost::spirit::closure<calc_closure, double> { member1 val; }; //定义ContextT策略为calc_closure::context_t rule<phrase_scanner_t, calc_closure::context_t> factor, term, exp; //直接使用phoenix的lambda表达式作为Actor factor = real_p[factor.val = arg1] | ('(' >> exp[factor.val = arg1] >> ')'); term = factor[term.val = arg1] >> *(('*' >> factor[term.val *= arg1]) | ('/' >> factor[term.val /= arg1])); exp = term[exp.val = arg1] >> *(('+' >> term[exp.val += arg1]) | ('-' >> term[exp.val -= arg1])); const char *szExp = "1 + (2 * (3 / (4 + 5)))"; double result; parse_info<> r = parse( szExp , exp[assign_a(result)], space_p); cout << szExp; if(r.full) { //成功,得到结果 cout << " = " << result << endl; } else { //失败,显示错误位置 cout << endl << string(r.stop - szExp, ' ') << '^' << endl; } return 0; }