Prevent user from deriving from incorrect CRTP base

前端 未结 6 887
感动是毒
感动是毒 2020-12-14 01:53

I cannot think about a proper question title to describe the problem. Hopefully the details below explains my problem clear.

Consider the following code



        
6条回答
  •  伪装坚强ぢ
    2020-12-14 02:45

    1) make all constructors of Base private (if there are no constructors, add one)

    2) declare Derived template parameter as friend of Base

    template 
    class Base
    {
    private:
    
      Base(){}; // prevent undesirable inheritance making ctor private
      friend  Derived; // allow inheritance for Derived
    
    public :
    
      void call ()
      {
          static_cast(this)->call_impl();
      }
    };
    

    After this it would be impossible to create any instances of the wrong inherited D2.

提交回复
热议问题