Template type check C++

前端 未结 6 777
日久生厌
日久生厌 2021-01-14 17:48

I have a template function which takes in objects. I need to determine whether the object is derived from a particular base class. If it is derived from the base class, I ne

6条回答
  •  春和景丽
    2021-01-14 18:51

    You can use Run Time Type Identification (RTTI) for this purpose. An Example follows:

    class A{
    public:
    virtual void func(){cout << "Base" << endl;}
    virtual ~A(){}
    };
    
    class B:public A{
    public:
    void func(){cout << "Derived" << endl;}
    };
    
    int main(){
    A * d1 = new B();
    B * d2;
    
    d1 -> func() ;
    
    d2 = dynamic_cast(d1);
    
    if(d2 != NULL)
           cout << "Base exists" << endl;
    else
           cout << "No relation" << endl;
    
    return 0;
    }
    

提交回复
热议问题