Downcasting from base pointer to templated derived types

前端 未结 4 1994
夕颜
夕颜 2021-02-01 11:06

I have the following hierarchy:

class base
{
public:
   virtual ~base(){}
   virtual void foo() {}
};

template 
class derived1 : public base
{         


        
4条回答
  •  时光说笑
    2021-02-01 11:24

    Solution 1: add one more virtual function:

    enum DerivedType
    {
        One,
        Two,
        ...
    };
    
    class base 
    { 
    public: 
       ~base(){} 
       virtual void foo() {}
       virtual DerivedType GetType() = 0;
    }; 
    
    template  
    class derived1 : public base 
    { 
       virtual void foo() {};
       virtual DerivedType GetType() { return One; }
    }; 
    
    template  
    class derived2 : public base 
    { 
       virtual void foo() {};
        virtual DerivedType GetType() { return Two; }
    }; 
    

    Solution 2: using tag classes:

    class Base
    {
    public:
        virtual ~Base() { }
    };
    
    class Derived1Tag
    { };
    
    class Derived2Tag
    { };
    
    template 
    class Derived1 : public Base, public Derived1Tag
    { };
    
    template 
    class Derived2 : public Base, public Derived2Tag
    { };
    
    
    int main(int argc, char** argv)
    {
        Derived1 d1;
        Derived2 d2;
    
        cout << dynamic_cast((Base*)&d1) << endl;
        cout << dynamic_cast((Base*)&d2) << endl;
    
        return 0;
    }
    

提交回复
热议问题