从模板参数继承类

C++: Inherit class from template parameter

本文关键字:继承 参数      更新时间:2023-10-16

我最近看到了下面的c++代码片段

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

,我想知道在什么情况下这样的设计是好的做法?

我理解它的方式是,将超类作为模板参数允许 a 的用户在实例化 a 的对象时选择超类。

但是如果是这样的话,对于所有用作模板实参的类(B),如果有一个共同的超类C,并且让 a 扩展C,岂不是更好吗?

通常用于实现静态多态性。

用例如下:

  • 基于策略的设计
  • 奇怪的重复模板模式
  • Barton-Nackman技巧

通常,您可以从动态多态性中获益,而不需要虚函数的额外运行时成本。但是只有当具体类型可以在编译时确定时,它才有用。

听起来像是包装器类的一个很好的候选:

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 <typename T>
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<d1> w1;
}

例如,包装类可以提供对派生类的同步访问。

它经常用于所谓的"基于策略的"设计中,即通过与期望的派生类组合向基类添加特征,参见Andrei Alexandrescu的"现代c++设计:泛型编程和设计模式的应用"。您从中派生的实例化模板类称为"策略"。这样的设计有时比继承更好,因为它允许组合策略并避免基于继承的模型中不可避免的组合爆炸。

请看下面的简单代码,其中REDBLUEPen绘制策略:

#include <iostream>
#include <string>
struct RED
{
    std::string getColor()
    {
        return "RED";
    }
};
struct BLUE
{
    std::string getColor()
    {
        return "BLUE";
    }
};
template <typename PolicyClass>
class Pencil: public PolicyClass
{
public:
    void Draw()
    {
        std::cout << "I draw with the color " << PolicyClass::getColor() << std::endl; 
    }
};

int main()
{   
    Pencil<RED> red_pencil; // Drawing with RED
    red_pencil.Draw();
    Pencil<BLUE> blue_pencil; // Different behaviour now
    blue_pencil.Draw();
    return 0;
}

可以在这里阅读更多内容:http://en.wikipedia.org/wiki/Policy-based_design

我使用这种风格的地方是我需要实现一个既易于使用又易于维护的通用图形库的地方过了一会儿,我想出了这样的设计:

GraphContainer,Edge,Node的抽象类:

template < class T1,class T2>
class  GraphAbstractContainer
{
public:
    using Node = T1;
    using Edge = T2;
    virtual std::list<Node> getConnectedNodes(const Node& node)const = 0;
    virtual Node addNode(const Node&) = 0;
    //...
};
class  GraphAbstracthNode
{
public:
    virtual uint32_t getId() const = 0;
    virtual void setID(uint32_t id)=0;
    //..
};
template<class T>
class  GraphAbstractEdge
{
public:
    using Node = T;
    //GraphAbstractEdge(){}
    virtual Node  firstNode() const = 0;
    virtual Node   secondNode() const = 0;
    virtual void  setFirstNode(const Node& node)  = 0;
    virtual void  setSecondNode(const Node& node) = 0;
    //...
};

然后我通过直接继承模板参数添加Adj_List和Adj矩阵实现。

例如,My Adj List类看起来像这样:

template<class T1 = GraphAbstractContainer<GraphAdjNode,
                   GraphAdjEdge>>
class  GraphAdjListContainer : public T1
{
public:
    using Node = typename T1::Node;
    using Edge = typename T1::Edge;
    //return connected Nodes
    virtual std::list<Node> getConnectedNodes(const Node& node) const
    {
        //..
    }
    //..
  };
};
template<class T>
class  GraphAdjNode : public T
{
public:
    //implementing abstract class methods...
};
template<class T>
class  GraphAdjEdge : public T
{
public:
   //...
};

我的图形类也直接从模板继承:

template<class GraphContainer=GraphAdjListContainer<>>
    class   Graph :public  GraphContainer
    {
    public:
        using Node = typename GraphContainer::Node;
        using Edge = typename GraphContainer::Edge;
         //...
}

这种设计模式的一个优点是你可以简单地通过继承抽象类和填充模板参数来改变整个类的底层内容。

为例,我定义Trie数据结构的方式如下:

class TrieNode :public GraphAdjNode
{
public:
    //...
    std::string word_;
};
class Trie 
{
public:
    using Graph = Graph < ecv::GraphAdjListContainer<TrieNode, ecv::GraphAdjListEdge<TrieNode>>>;
    using Node =  Graph::Node;
    using Edge =  Graph::Edge;
    void addWord(wstring word);
    //...
private:
    Graph graph_;
}