CRTP with Protected Derived Member

前端 未结 3 722
半阙折子戏
半阙折子戏 2021-01-30 11:19

In the CRTP pattern, we run into problems if we want to keep the implementation function in the derived class as protected. We must either declare the base class as a friend of

3条回答
  •  暖寄归人
    2021-01-30 11:34

    It's not a problem at all and is solved with one line in derived class:

    friend class Base< Derived >;

    #include 
    
    template< typename PDerived >
    class TBase
    {
     public:
      void Foo( void )
      {
       static_cast< PDerived* > ( this )->Bar();
      }
    };
    
    class TDerived : public TBase< TDerived >
    {
      friend class TBase< TDerived > ;
     protected:
      void Bar( void )
      {
       std::cout << "in Bar" << std::endl;
      }
    };
    
    int main( void )
    {
     TDerived lD;
    
     lD.Foo();
    
     return ( 0 );
    }
    

提交回复
热议问题