I cannot think about a proper question title to describe the problem. Hopefully the details below explains my problem clear.
Consider the following code
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.