Boost semantic actionは「解析時アクション」や「セマンティックアクション」と呼ばれるが、
用は[ ]でくくった18行目の[&display]がポイントである。
この[ ]の中の関数display(7行目で定義)が、入力が整数にである場合(int_p)呼び出される。
1#include <iostream>
2#include <string>
3#include <boost/spirit.hpp>
4using namespace std;
5using namespace boost::spirit;
6
7void display( int x ) { cout << "you typed: " << x << endl; }
8
9struct IntDisplay : grammar<IntDisplay>
10{
11 template<typename ScannerT>
12 struct definition
13 {
14 typedef rule<ScannerT> rule_t;
15 rule_t r;
16 definition( const IntDisplay& )
17 {
18 r = int_p[&display] % ',';
19 }
20 const rule_t& start() const { return r; }
21 };
22};
23
24int main()
25{
26 IntDisplay parser;
27
28 string line;
29 while( cout<<"# ", getline(cin, line) )
30 {
31 parse_info<string::const_iterator> info =
32 parse( line.begin(), line.end(), parser, space_p );
33 cout << (info.full ? "OK" : "fail") << endl;
34 }
35 return 0;
36}
実行してみる。。。
# g++ boost-semantic-action.cpp -lboost_system
# ./a.out
# 3
you typed: 3
OK
# 555
you typed: 555
OK
これの発展版にディレクティブといふのがある。(`ー´)b