趣味のプロジェクトの一環として、2D ゲーム エンジンのイベント システムを作成しています。イベント システム設計の一環として、オブジェクトが表すテンプレート化された派生クラスに基づいて、オブジェクトをマップする必要があります。問題をよりよく説明するために、次の単純化されたコードを検討してください。
class Base
{
public:
virtual ~Base(){};
int getTypeId() {return typeId_;}
static bool compareIfSameType(Base *a, Base *b)
{return a->getTypeId() == b->getTypeId();}
protected:
int typeId_;
};
template<typename T>
class Derived : public Base
{
public:
Derived(int typeId) {typeId_ = typeId;}
};
int main()
{
Derived<int> obj1(1);
Derived<float> obj2(2);
Derived<float> obj3(2);
if(Base::compareIfSameType(&obj1, &obj2))
cout << "obj1 and obj2 are of equal type\n";
else cout << "obj1 and obj2 are not of equal type\n";
if(Base::compareIfSameType(&obj2, &obj3))
cout << "obj2 and obj3 are of equal type\n";
else cout << "obj2 and obj3 are not of equal type\n";
}
/*output:
obj1 and obj2 are not of equal type
obj2 and obj3 are of equal type*/
このコードには実際の問題はありませんが、各派生クラス インスタンスの型を識別する番号を手動で渡す必要があるため、非常に面倒で、エラーが発生しやすくなります。私が望むのは、コンパイル時に T の型から typeId を自動的に生成することです。
Derived<int> obj1;
Derived<float> obj2;
Derived<float> obj3;
if(Base::compareIfSameType(&obj1, &obj2))
//do something...