C++: Inherit class from template parameter

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

    It is used frequently in the so called "policy-based" design, i.e. you add characteristics to a base class by composition with desired derived classes, see "Modern C++ Design: Generic Programming and Design Patterns Applied" by Andrei Alexandrescu. The instantiated template class from which you derive is called the "policy". Such a design is sometimes better than inheritance, as it allows to combine policies and avoid a combinatorial explosion inevitable in the inheritance-based model.

    See for example the following simple code, where RED and BLUE are drawing policies for a Pen:

    #include 
    #include 
    
    struct RED
    {
        std::string getColor()
        {
            return "RED";
        }
    };
    
    struct BLUE
    {
        std::string getColor()
        {
            return "BLUE";
        }
    };
    
    template 
    class Pencil: public PolicyClass
    {
    public:
        void Draw()
        {
            std::cout << "I draw with the color " << PolicyClass::getColor() << std::endl; 
        }
    };
    
    
    int main()
    {   
        Pencil red_pencil; // Drawing with RED
        red_pencil.Draw();
        Pencil blue_pencil; // Different behaviour now
        blue_pencil.Draw();
    
        return 0;
    }
    

    Can read a bit more here: http://en.wikipedia.org/wiki/Policy-based_design

提交回复
热议问题