Downcasting from base pointer to templated derived types

前端 未结 4 1998
夕颜
夕颜 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

    Move the logic which depends on the type into the type.

    Instead of:

    if (dynamic_cast*>(b) ||
        dynamic_cast*>(b) ||
        dynamic_cast*>(b))
      std::cout << "is derived1";
    else if (dynamic_cast*>(b) ||
        dynamic_cast*>(b) ||
        dynamic_cast*>(b))
      std::cout << "is derived2";
    

    add a virtual print_name() const function to base, and then do:

    void example() {
        std::unique_ptr b(new derived1());
        b->print_name();
    }
    class base
    {
    public:
       ~base(){}
       virtual void foo() {}
       virtual void print_name() const = 0;
    };
    
    template 
    class derived1 : public base
    {
       virtual void foo() {}
       virtual void print_name() const {
           std::cout << "is derived1";
       }
    };
    
    template 
    class derived2 : public base
    {
       virtual void foo() {}
       virtual void print_name() const {
           std::cout << "is derived2";
       }
    };
    

提交回复
热议问题