mixing templates with polymorphism

前端 未结 2 569
逝去的感伤
逝去的感伤 2020-12-02 01:07
class A
{
    friend void foo();
    virtual void print_Var() const{};

};// does not contain variable Var;


template
class B : public A
{
    T Var;         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 01:41

    I think it will be the easiest way. Just move the comparison method to the interface and override it in derived classes. Add the following lines to yor example:

    class A
    {
       /*..................................................*/
       virtual bool comp(const int) const { return false; }
       virtual bool comp(const std::string) const { return false; }
       virtual bool comp(const double) const { return false; }  
    };
    
    template
    class B : public A
    {
       /*..................................................*/
       virtual bool comp(const T othr) const override { return othr == Var; }
    };
    
    void foo()
    {
          /*..................................................*/
          if (i->comp(20))
          {
             /* do something*/
          }
    
          if (i->comp("Hello Stackoverflow"))
          {
             /* do something*/
          }
          /*..................................................*/
    }
    

提交回复
热议问题