私の質問は、オブジェクトが別のオブジェクトの型階層に属しているかどうかを確認しようとしている C++ の RTTI に関連しています。BelongsTo() メソッドはこれをチェックします。typeid を使用してみましたが、エラーがスローされ、実行時に変換するターゲット型を見つける方法が他にわかりません。
#include <iostream>
#include <typeinfo>
class X
{
public:
// Checks if the input type belongs to the type heirarchy of input object type
bool BelongsTo(X* p_a)
{
// I'm trying to check if the current (this) type belongs to the same type
// hierarchy as the input type
return dynamic_cast<typeid(*p_a)*>(this) != NULL; // error C2059: syntax error 'typeid'
}
};
class A : public X
{
};
class B : public A
{
};
class C : public A
{
};
int main()
{
X* a = new A();
X* b = new B();
X* c = new C();
bool test1 = b->BelongsTo(a); // should return true
bool test2 = b->BelongsTo(c); // should return false
bool test3 = c->BelongsTo(a); // should return true
}
同じ型階層に多くのクラスがあるため、メソッドを仮想化して派生クラスに任せるのは悪い考えのようです。または、同じことを行うための他の/より良い方法を知っている人はいますか? 提案してください。
更新: b.BelongsTo(a) は、入力オブジェクト型 (a) が型階層内の現在のオブジェクト (b) の祖先であるかどうかを検出する必要があります。