• 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/p/1956882.html
Copyright © 2020-2023  润新知