C++: Impl of RTTI
#include <stdio.h>
#define CHECK(x) {if(!(x)) printf("ERROR " #x " @Line %d\n", __LINE__);}
struct TypeInfo
{
char* m_name;
const TypeInfo* m_parent;
TypeInfo(char* name, const TypeInfo* parent)
:m_name(name), m_parent(parent)
{
}
};
class A
{
static TypeInfo typeInfo_a;
public:
static const TypeInfo* GetType()
{
return &typeInfo_a;
}
};
TypeInfo A::typeInfo_a("A", NULL);
class B:public A
{
static TypeInfo typeInfo_b;
public:
static const TypeInfo* GetType()
{
return &typeInfo_b;
}
};
TypeInfo B::typeInfo_b("A", A::GetType());
template <class A, class B>
bool IsBaseOf()
{
for( const TypeInfo* typeinfo = B::GetType(); typeinfo; typeinfo = typeinfo->m_parent )
{
if( typeinfo == A::GetType() )
return true;
}
return false;
}
template <class A, class B>
bool IsBaseOf2(const A* pa, const B* pb)
{
for( const TypeInfo* typeinfo = pb->GetType(); typeinfo; typeinfo = typeinfo->m_parent )
{
if( typeinfo == pa->GetType() )
return true;
}
return false;
}
int main( int argc, char **argv )
{
CHECK((IsBaseOf<A,B>()));
CHECK((!IsBaseOf<B,A>()));
A a;
B b;
A &pb=b;
CHECK(IsBaseOf2(&a,&b));
CHECK(!IsBaseOf2(&b,&a));
CHECK(IsBaseOf2(&a,&pb));
CHECK(!IsBaseOf2(&pb,&a));
return 0;
}
#define CHECK(x) {if(!(x)) printf("ERROR " #x " @Line %d\n", __LINE__);}
struct TypeInfo
{
char* m_name;
const TypeInfo* m_parent;
TypeInfo(char* name, const TypeInfo* parent)
:m_name(name), m_parent(parent)
{
}
};
class A
{
static TypeInfo typeInfo_a;
public:
static const TypeInfo* GetType()
{
return &typeInfo_a;
}
};
TypeInfo A::typeInfo_a("A", NULL);
class B:public A
{
static TypeInfo typeInfo_b;
public:
static const TypeInfo* GetType()
{
return &typeInfo_b;
}
};
TypeInfo B::typeInfo_b("A", A::GetType());
template <class A, class B>
bool IsBaseOf()
{
for( const TypeInfo* typeinfo = B::GetType(); typeinfo; typeinfo = typeinfo->m_parent )
{
if( typeinfo == A::GetType() )
return true;
}
return false;
}
template <class A, class B>
bool IsBaseOf2(const A* pa, const B* pb)
{
for( const TypeInfo* typeinfo = pb->GetType(); typeinfo; typeinfo = typeinfo->m_parent )
{
if( typeinfo == pa->GetType() )
return true;
}
return false;
}
int main( int argc, char **argv )
{
CHECK((IsBaseOf<A,B>()));
CHECK((!IsBaseOf<B,A>()));
A a;
B b;
A &pb=b;
CHECK(IsBaseOf2(&a,&b));
CHECK(!IsBaseOf2(&b,&a));
CHECK(IsBaseOf2(&a,&pb));
CHECK(!IsBaseOf2(&pb,&a));
return 0;
}