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;
}

原文链接: https://www.cnblogs.com/cutepig/archive/2011/02/17/1956882.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++: Impl of RTTI

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/21114

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月7日 下午11:08
下一篇 2023年2月7日 下午11:08

相关推荐