Policy based design and best practices - C++

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

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


        
4条回答
  •  生来不讨喜
    2020-12-23 02:56

    This looks like a nice example of policy-based smart pointer implementation: link. Andrei Alexandrescu describes policy-based smart pointer implementation in one of his books. As to your questions now. I have some experience in this stuff but not enough to take my words for granted:

    Ad 1 & 4. I guess policy-based design is more about templates than inheritance. You write a template class and template arguments are policy classes, like that:

    template
    class Baz {
        // implementation goes here
    };
    

    Then you use methods from policy classes in your class:

    void Baz::someMethod(int someArg) {
        FooPolicy::methodInit();
        // some stuff
        BarPolicy::methodDone();
    }
    

    I use static methods in this example because often policy doesn't require any state. If it does, you incorporate policy's state by composition, not by inheritance:

    template
    class Baz {
      private:
        FooPolicy::State fooState; // might require 'typename' keyword, I didn't
                                   // actually tried this in any compiler
        // rest of the Baz class
    };
    

    Ad 2. You can write a template specialization - for a particular combination of main class and it's policies you can write a special version of any method or constructor, AFAIK:

    template <>
    Baz::Baz(someArgument)
       : fooState(someArgument)
    {
        // stuff here
    }
    

    Hope it helps you a bit,

    Mike

提交回复
热议问题