Policy based design and best practices - C++

前端 未结 4 1288
别那么骄傲
别那么骄傲 2020-12-23 02:12
struct InkPen
{
  void Write()
  {
    this->WriteImplementation();
  }

  void WriteImplementation()
  {
    std::cout << \"Writing using a inkpen\" <&l         


        
4条回答
  •  抹茶落季
    2020-12-23 03:05

    Here's how I would implement the class:

    template
    class Writer
    {
    public:
      Writer(const PenType& pen = PenType()) : pen(pen) {}
    
      void StartWriting()
      {
        pen.Write();
      }
    
    private:
      PenType pen;
    };
    

    This allows the user to pass a specific Pen object to the constructor, if it either doesn't have a default constructor, or you don't want it to be used, and second, it still allows you to omit the PenType object if you're happy to let it create one with the default constructor. The C++ standard library does the same in many classes (think of the allocators for container classes for example).

    I removed the inheritance. It didn't really seem to add anything (and might cause problems. You probably don't want the user of the Writer class to call the PenType::Write function directly. You could use private inheritance instead, but often, composition is a simpler and more conventional design.

    In general, policy-based design does not require inheritance. Adding it as a member works just as well. If you do go for inheritance, make it private so you don't get the problem you mentioned as #4.

提交回复
热议问题