C++: Inherit class from template parameter

后端 未结 4 1059
臣服心动
臣服心动 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:20

    A place where I use this style was where I need to implement a generic graph library which is both easy to use and also easy to maintain After a while I came with this design :

    ABstract class for GraphContainer,Edge,Node :

    template < class T1,class T2>
    class  GraphAbstractContainer
    {
    public:
        using Node = T1;
        using Edge = T2;
        virtual std::list 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  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;
        //...
    
    };
    

    Then I add Adj_List and Adj Matrix implementation by inheriting directly from template parametrs .

    for example My Adj List classess looks some thing like this :

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

    And also My Graph class inherit directly from template too :

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

    An advantage for this design pattern is you can simply change the whole class underlying's stuffs by just inherit from abstract classes and fill the template parametrs.

    for example I define Trie data structure by simply doing this :

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

提交回复
热议问题