How to ensure that the template parameter is a subtype of a desired type?

Given some complete type MyBase, the following will yield a compile-time error if T is not derived 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’re using a C++03 compiler with TR1, you can use std::tr1::is_base_of instead of boost::is_base_of; if you’re using a C++11 compiler, you can use std::is_base_of instead of boost::is_base_of and the static_assert 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
};

N.b. this will yield true_type for privately and ambiguously-derived types, so this is insufficient if what you really need is to treat T as-a MyBase (in most contexts).

Doc links:
Boost.StaticAssert
Boost.TypeTraits

Leave a Comment