| High Integrity CPP Guideline 16.4 | Only use templates when the behaviour of the class or function template is completely independent of the type of object to which it is applied. |
| Justification |
If behaviour varies with the type of object, inheritance with virtual functions should be used. Templates should implement genericity and should be applicable to any type that meets the interface requirements specified in the template definition.
template< typename T > void foo( T t )
{
// Avoid: a template definition should not have behaviour
// defined by the dynamic types of template arguments
//
if ( 0 != dynamic_cast< SomeType* >( t ) )
{}
}
template< typename T > void bar( T t )
{
// Prefer: this template works with any type that provides
// the member someFunction in its interface
//
t.someFunction();
}
|