Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict C++ Template Parameter to Subclass

Tags:

c++

templates

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();  } 
like image 545
phant0m Avatar asked Jul 04 '10 15:07

phant0m


People also ask

How will you restrict the template for a specific datatype?

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.

Can we pass Nontype parameters to templates?

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.

Can template class inherit?

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.

Can a template function override?

You cannot define a virtual template method. override only works for virtual methods, and you can only override methods with the same signature.


1 Answers

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.

like image 160
Vish Desai Avatar answered Sep 20 '22 08:09

Vish Desai