C++: Inherit class from template parameter

后端 未结 4 1067
臣服心动
臣服心动 2021-01-30 14:18

I recently saw the following C++ code-snippet

template 
class A : public B
{
   ...
};

and I am wondering in which setting such

4条回答
  •  长发绾君心
    2021-01-30 15:13

    Sounds like a good candidate for a wrapper class:

    class base {
    public:
      virtual void f() = 0;
    };
    
    class d1 : public base {
    public:
      virtual void f() override { ... };
    };
    
    class d2 : public base {
    public:
      virtual void f() override { ... };
    };
    
    template 
    class wrapper : public T {
    public:
      virtual void f() override {
        pre_op();
        T::f();
        post_op();
      }
    
    private:
      void pre_op() { ... }
      void post_op() { ... }
    }
    
    int main(int, char**) {
      wrapper w1;
    }
    

    For example, the wrapper class can provide synchronized access to the derived classes.

提交回复
热议问题