I just had a case where I wanted to make sure that a C++ template parameter was of a certain type. The template should be used for pointers to instances of class “Base” and its derivates so that I could call a method of Base on the object provided to the template class.
template< class T > class MyTemplate { public: MyTemplate( T object ) { object->baseClassMethod(); } };
First, I thought there would be no way to achieve this, but then I tried a static_cast which turned out to be the solution: using the static_cast ensures that the type casted to is used at compile-time. Isn’t that beautiful? If you don’t need to access the object but constrain the template to a certain type, you could use the d’tor to implement some dummy code.
template< class T > class MyTemplate { public: MyTemplate( T someObject ) { } virtual ~MyTemplate() { // constrain parameter type to "Base" // and derivates static_cast< Base* >( static_cast< T >( 0 ) ); } };
Using this template with a type which is neither “Base” nor inherited from “Base” leads to a compiler error like “can’t convert ‘bad type’ to ‘Base’.