C++ のテンプレート関数へのポインタ
ある文字列をキー、それに対するクラスを値とするような map なり何なりをあらかじめ作っておいて、入力値である文字列によって生成されるオブジェクトを決定したい、みたいな状況に遭遇しました。
if キー1 オブジェクト 1 生成、if キー 2 オブジェクト 2 生成、みたいな実装にすると、キーが増える度にこの実装も変更しないといけないのが嫌で、対応するクラスを作って map なりに 1 行追加するだけで良いようなコードにしたかったのです。
で、どないしたらええやろと考えた結果、以下みたいに実装してみました。
-
#include <iostream>
-
#include <string>
-
#include <map>
-
-
class Base {
-
public:
-
virtual void hello() = 0;
-
};
-
-
class A : public Base {
-
public:
-
A() {
-
cout <<"A Constructor" <<endl;
-
}
-
void hello() {
-
cout <<"I'm A" <<endl;
-
}
-
};
-
-
class B : public Base {
-
public:
-
B() {
-
cout <<"B Constructor" <<endl;
-
}
-
void hello() {
-
cout <<"I'm B" <<endl;
-
}
-
};
-
-
template<class T>
-
Base* create() {
-
return new T;
-
}
-
-
int main(int argc, char* argv[]) {
-
typedef Base* (*CREATEFUNC)();
-
-
map<string, CREATEFUNC> m;
-
m.insert(pair<string, CREATEFUNC>("A", &create<A>));
-
m.insert(pair<string, CREATEFUNC>("B", &create<B>));
-
-
for (map<string, CREATEFUNC>::const_iterator cit = m.begin();
-
cit != m.end();
-
c++it) {
-
Base* p = (cit->second)();
-
p->hello();
-
}
-
-
return 0;
-
}
テンプレートで指定したクラスを new して返すだけの関数を作って、それへのポインタを map のメンバとすることで、イテレータで回しながら new していってます。Base クラスで load とか save とかを純粋仮想関数としておいて(上でいう hello ですね)、追加するクラスにその実装を強制しておけば良い感じ。
テンプレート関数へのポインタに関するページをあまり見つけられなかったので書いておきました。
(2006/11/03 追記)
http://forums.belution.com/ja/cpp/000/048/99.shtml を見つけました。

No comments
Jump to comment form | comments rss [?] | trackback uri [?]