开发者

Method of derived class needs to downcast its parameter

开发者 https://www.devze.com 2022-12-19 03:30 出处:网络
Here is a sample code: class Base { public: virtual void common(); }; class Derived { public: void common();

Here is a sample code:

class Base {
public:
    virtual void common();
};

class Derived {
public:
    void common();
    virtual void spec(); // added function specific for this class
};

class BaseTracker {
public:
    void add(Base* p);
private:
    vector < Base* > vec;
};

class DerivedTracker {
public:
    void ad开发者_JAVA技巧d(Derived* p);
private:
    vector < Derived* > vec;
};

I want DerivedTracker and BaseTracker to be derived from class Tracker, because a lot of code for these two classes is the same, except one method, add(). DerivedTracker::add() method needs to call functions specific to Derived class. But I don't want to do dynamic casting. I think it is not the case when I should use it. Also Tracker class should include container, so functions which are implemented in this class could use it.


It sounds like the Tracker class would best be a template instead of being derived from a common ancestor:

template<typename Element>
class Tracker {
public:
   void add(Element* p);
private:
   vector< Element* > vec;
};

typedef Tracker<Base> BaseTracker;
typedef Tracker<Derived> DerivedTracker;

You could then add a specialization of the add() method that uses Derived's special features:

template<>
void Tracker<Derived>::add(Derived* p) {
  p->spec();
  vec.push_back(p);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消