zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    Java数据结构与算法(15)
    SpringJMS解析--使用示例
    Java数据结构与算法(14)
    Java数据结构与算法(13)
    Java数据结构与算法(12)
    如何实践设计原则-面向对象设计原则
    软件架构的两大流派:组成派、决策派
    软件 可变与不可变 及封装可变性
    Java数据结构与算法(11)
    搭建本地yum仓库及自制rpm包(无需镜像)
  • 原文地址:https://www.cnblogs.com/cutepig/p/1956882.html
Copyright © 2011-2022 走看看