How can I force a template parameter T
to be a subclass of a specific class Baseclass
? Something like this:
template <class T : Baseclass> void function(){ T *object = new T(); }
There are ways to restrict the types you can use inside a template you write by using specific typedefs inside your template. This will ensure that the compilation of the template specialisation for a type that does not include that particular typedef will fail, so you can selectively support/not support certain types.
Template non-type arguments in C++It is also possible to use non-type arguments (basic/derived data types) i.e., in addition to the type argument T, it can also use other arguments such as strings, function names, constant expressions, and built-in data types.
Inheriting from a template classIt is possible to inherit from a template class. All the usual rules for inheritance and polymorphism apply. If we want the new, derived class to be generic it should also be a template class; and pass its template parameter along to the base class.
You cannot define a virtual template method. override only works for virtual methods, and you can only override methods with the same signature.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With