LoginSignup
0
0

More than 3 years have passed since last update.

ログ解析者がC++テンプレートプログラミングをかじった結果。。。(2)

Last updated at Posted at 2020-10-26

C++テンプレートプログラミングという技術がある。
聞くところには、Javaにはないという。。

ログ解析者にとっては、そのまんまだが、「えらく難しい。」(*´Д`)
SFINAE, CRTP などは特に難しいので、とばす。

ログ解析について関係しそうなのは、Boost.Multi-indexなどであると狙いをつける。
Boost.Multi-indexはコンテナとしてログ解析に使えそうである。(`ー´)b

Multi-indexはポリシーを元に実装されているらしい。
なかでも、「パラメータ化継承」という技術を使っている。
パラメータ化継承とは、継承元のクラスをテンプレートパラメータ<...>によって決められる。

コードを見てみる。。

 1#include <iostream>
 2#include <string>
 3
 4using namespace std;
 5
 6class text
 7{
 8public:
 9  text() {}
10  ~text() {}
11  string out(const string& str) const { return str; }
12};
13
14template <class Base>
15class p : public Base {
16public:
17  string out(const string& str) const { return "<p>" + Base::out(str) + "</p>"; }
18};
19
20template <class Base>
21class a : public Base {
22public:
23  string out(const string& str) const { return "<a>" + Base::out(str) + "</a>"; }
24};
25
26int main(int argc, char *argv[])
27{
28
29  /*                                                                                                                                                                                    
30  a<p> hoge0;                                                                                                                                                                           
31  cout << hoge0.out("fuga") << endl;                                                                                                                                                    
32  */
33
34  a<text> hoge1;
35  cout << hoge1.out("fuga") << endl;
36
37  p<text> hoge2;
38  cout << hoge2.out("fuga") << endl;
39
40  p<a<text> > hoge3;
41  cout << hoge3.out("fuga") << endl;
42
43  a<p<text> > hoge4;
44  cout << hoge4.out("fuga") << endl;
45
46  // output: <a><p>fuga</p></a>                                                                                                                                                         
47  return 0;
48}

↓は通常の(というか普通の)継承であるが、


    34  a < text > hoge1;
    35  cout << hoge1.out("fuga") << endl;
    36
    37  p < text > hoge2;
    38  cout << hoge2.out("fuga") << endl;

↓ は、テンプレートパラメータが、a<text> とp<text>で違っている。


    40  p < a < text > > hoge3;
    41  cout << hoge3.out("fuga") << endl;
    42
    43  a < p < text > > hoge4;
    44  cout << hoge4.out("fuga") << endl;

実行してみる。。。

result.png

a<text> とp<text> の場合で結果が違っている。。。
a<text> とp<text>をおそらく、ポリシーと呼ぶ。。。

パラメータ化継承を図にするとこうなる。

parameterized-inheritance.png

↑こうすると、なにやら関数型の気配がしてくる。

multi-indexのコードをみてみる。。

cpptp-book-2nd.png

おそらくだが、
<sequenced>と<ordered_unique<identity<T>>がポリシーであり、
これらによって継承元のクラスが変わる。

継承元のクラスは、push_backを実装しているものもあるし、insertを実装しているものもあるということではないだろうか?

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0