I recently saw the following C++ code-snippet
template <class B> class A : public B { ... };
and I am wondering in which setting such a design is good practice?
The way I understand it, is that having the superclass as a template parameter allows users of A to choose a superclass when instantiating an object of A.
But if this is the case, wouldn't it be better to have a common superclass C for all the classes (B) which are used as the template argument and have A extend C ?
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.
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.
Accessing template base class members in C++ In order to access a member (method or field) of a templated base class, you need to either use the “this” pointer or use the explicit name of the base class with template arguments. without “this->” in front of “this->x”, it would not be able to find the member.
" typename " is a keyword in the C++ programming language used when writing templates. It is used for specifying that a dependent name in a template definition or declaration is a type.
It's often used to realize static polymorphism.
Use cases are:
In general you have the benefits from dynamic polymorphism, without the extra runtime costs of virtual functions. But it's only useful if the concrete type can be determined at compile time.
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