It's quite common, actually almost all templates have certain requirements towards their arguments. Those are usually implicitly clear from how the template parameter is used, but you can improve the error messages by using type traits. In C++11, they are available from the standard library via #include <type_traits>
, otherwise look into Boost.TypeTraits.
With C++11, the usage is quite simple when you also use static_assert
:
template< typename T >
std::shared_ptr< T > spawn()
{
// make this the first line in your function to get errors early.
// also note that you can use any compile-time check you like.
static_assert( std::is_base_of< Monster, T >::value,
"T is not derived from Monster" );
// the rest of your code follows here.
// ...
// return ...;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…