【问题标题】:Can a class inherit from both an abstract class and a CRTP class?一个类可以同时继承抽象类和 CRTP 类吗?
【发布时间】:2013-01-31 22:03:51
【问题描述】:

一个类可以同时继承抽象类和CRTP类吗?或者,如果我从一个 CRTP 类继承,我所继承的所有类都必须使用 CRTP?

【问题讨论】:

  • 你为什么不测试呢? ;)

标签: c++ templates inheritance abstract-class crtp


【解决方案1】:

一个类可以继承抽象类和CRTP类吗?

为什么不呢?是的,可以。

或者,如果我从一个 CRTP 类继承,我所继承的所有类都必须使用 CRTP?

为什么会这样?不,他们不必这样做。

【讨论】:

    【解决方案2】:

    是的。

    class AbstractBase {
    public:
      virtual ~AbstractBase() {}
      virtual void Function() =  0;
    };
    
    template<class T>
    class CRTPBase {
    public:
      void Function2() {}
    };
    
    class Derived : public AbstractBase, public CRTPBase<Derived> {
    public:
      void Function() {}
    };
    
    int main () {
      Derived d;
      d.Function();
      d.Function2();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-03
      • 1970-01-01
      • 2012-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多