Boost.Spiritについて少しメモした


C++ Boost(またはテンプレートプログラミング)の最大のアプリケーションは何か?

→ 諸説あるが、Template ExpressionかSpiritのどちらかだらうという人は結構多い。

スクリプトエンジンプログラミングという名著がある。
https://www.sbcr.jp/product/4797347623/
私は、ここから、Boost.Spiritに入った。

Flex/Bisonとはまた違う世界である。

 1#include <iostream>
 2#include <string>
 3#include <boost/spirit.hpp>
 4using namespace std;
 5using namespace boost::spirit;
 6
 7struct Watashino_Grammar : grammar<Watashino_Grammar>
 8{
 9    template<typename ScannerT>
10      struct definition
11      {
12          typedef rule<ScannerT> rule_t;
13          rule_t r;
14
15          definition( const Watashino_Grammar& )
16          {
17              r = ch_p('b') >> *ch_p('a') >> ch_p('c');
18          }
19          const rule_t& start() const { return r; }
20      };
21};
22
23#include <typeinfo>
24int main()
25{
26    Watashino_Grammar 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 );
33        cout << (info.full ? "OK" : "fail") << endl;
34    }
35    return 0;
36}

7-21行目のScannerTとか、rule_tとかは、超絶技巧が使われているので、ここではあまり立ち入らない。(逃げる)
まず、どこを注意すればいいのかという話になりそうだが、これは15-18行目の部分である。

15          definition( const Watashino_Grammar& )
16          {
17              r = ch_p('b') >> *ch_p('a') >> ch_p('c');
18          }

次に、*ch_p('a')を見てみると、*が付いているが、これは任意の文字の繰り返し(0回も含む)という意味である。

実行してみる。。。


# g++ bac.cpp -lboost_system
In file included from bac.cpp:3:0:
/usr/include/boost/spirit.hpp:18:4: warning: #warning "This header is deprecated. Please use: boost/spirit/include/classic.hpp" [-Wcpp]
 #  warning "This header is deprecated. Please use: boost/spirit/include/classic.hpp"
# ./a.out 
# bac
OK
# baaac
OK
# bc
OK
# ba
fail
#  

https://www.sbcr.jp/product/4797347623/
↑を参考にしたBoostの特徴

■ Bison/Flexより小回りが利く。(ファイルを分けなくて良い等)
■ Bison/FlexはLALR(1)だが、Boostは再帰下降パーサ。(`ー´)b