How to simulate virtuality for method template

后端 未结 5 1043
忘了有多久
忘了有多久 2021-01-19 14:08

I have a class hierarchy where I want to introduce a method template that would behave like if it was virtual. For example a simple hierarchy:

class A {
  vi         


        
5条回答
  •  面向向阳花
    2021-01-19 14:38

    As you may know, you cannot have templates for virtual functions, since the entirety of the virtual functions is part of the class type and must be known in advance. That rules out any simple "arbitrary overriding".

    If it's an option, you could make the template parameter part of the class:

    template  class A
    {
    protected:
      virtual void method(T &);
    };
    
    template  class B : public A
    {
      virtual void method(T &); // overrides
    };
    

    A more involved approach might use some dispatcher object:

    struct BaseDispatcher
    {
      virtual ~BaseDispatcher() { }
      template  void call(T & t) { dynamic_cast(this)->method(t); }
    };
    struct ConcreteDispatcher : BaseDispatcher
    {
      template  void method(T &);
    };
    
    class A
    {
    public:
      explicit A(BaseDispatcher * p = 0) : p_disp(p == 0 ? new BaseDispatcher : p) { }
      virtual ~A() { delete p_disp; };
    private:
      BaseDispatcher * p_disp;
      template  void method(T & t) { p_disp->call(t); }
    };
    
    class B : public A
    {
    public:
      B() : A(new ConcreteDispatcher) { }
      // ...
    };
    

提交回复
热议问题