Prevent user from deriving from incorrect CRTP base

前端 未结 6 886
感动是毒
感动是毒 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:30

    There is no way to prevent the user from writing incorrect derived classes; however, there are ways to prevent your code from invoking classes with unexpected hierarchies. If there are points at which the user is passing Derived to the library functions, consider having those library functions perform a static_cast to the expected derived type. For example:

    template < typename Derived >
    void safe_call( Derived& t )
    {
      static_cast< Base< Derived >& >( t ).call();
    }
    

    Or if there are multiple levels of hierarchy, consider the following:

    template < typename Derived,
               typename BaseArg >
    void safe_call_helper( Derived& d,
                           Base< BaseArg >& b )
    {
       // Verify that Derived does inherit from BaseArg.
       static_cast< BaseArg& >( d ).call();
    }
    
    template < typename T >
    void safe_call( T& t )
    {
      safe_call_helper( t, t );  
    }
    

    In both of thse cases, safe_call( d1 ) will compile while safe_call( d2 ) will fail to compile. The compiler error may not be as explicit as one would like for the user, so it may be worthwhile to consider static asserts.

提交回复
热议问题