Given some complete MyBase type, the following will result in a compile-time error if T not obtained from MyBase :
#include <boost/type_traits/is_base_of.hpp> #include <boost/static_assert.hpp> template<typename T> class Foo { BOOST_STATIC_ASSERT_MSG( (boost::is_base_of<MyBase, T>::value), "T must be a descendant of MyBase" ); // Foo implementation as normal };
If you use the C ++ 03 compiler with TR1, you can use std::tr1::is_base_of instead of boost::is_base_of ; if you use the C ++ 11 compiler, you can use std::is_base_of instead of boost::is_base_of and the boost::is_base_of keyword instead of the BOOST_STATIC_ASSERT_MSG macro:
#include <type_traits> template<typename T> class Foo { static_assert( std::is_base_of<MyBase, T>::value, "T must be a descendant of MyBase" ); // Foo implementation as normal };
Nb this will give true_type for private and ambiguous derived types, so this is not enough if you really need to treat T as-a MyBase (in most contexts).
Doc links:
Boost StaticAssert
Boost Typetraits
ildjarn Aug 11 2018-11-11T00: 00Z
source share