Downcasting from base pointer to templated derived types

前端 未结 4 1999
夕颜
夕颜 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:30

    Insert a non-templated class inbetween base and derived1 or derived2:

    class base
    {
    public:
       virtual ~base() {}  // **NOTE** Should be virtual
       virtual void foo() {}
    };
    
    class derived1_base : public base
    {
    };
    
    template 
    class derived1 : public derived1_base
    {
    public:
       virtual void foo() {}
    };
    
    class derived2_base : public base
    {
    };
    
    template 
    class derived2 : public derived2_base
    {
    public:
       virtual void foo() {}
    };
    

    In a comment, you mentioned:

    [I want to] call a particular function for each one - btw there's more than derived1 and derived2

    Add that (virtual) function to derived1_base, and you don't even need to know T anymore.

    if (dynamic_cast(foo))
    {
      std::cout << "is derived1";
      dynamic_cast(foo)->specific_derived1_function();
    }
    else if (dynamic_cast(foo))
    {
      std::cout << "is derived2";
      dynamic_cast(foo)->specific_derived2_function();
    }
    

    NOTE: I consider a list of dynamic_cast<> a code smell, and I urge you to rethink your approach.

提交回复
热议问题