Restrict C++ Template Parameter to Subclass

Solution 1:

With a C++11 compliant compiler, you can do something like this:

template<class Derived> class MyClass {

    MyClass() {
        // Compile-time sanity check
        static_assert(std::is_base_of<BaseClass, Derived>::value, "Derived not derived from BaseClass");

        // Do other construction related stuff...
        ...
   }
}

I've tested this out using the gcc 4.8.1 compiler inside a CYGWIN environment - so it should work in *nix environments as well.

Solution 2:

In this case you can do:

template <class T> void function(){
    Baseclass *object = new T();

}

This will not compile if T is not a subclass of Baseclass (or T is Baseclass).