Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Inherit class from template parameter

Tags:

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 ?

like image 957
user695652 Avatar asked May 26 '14 11:05

user695652


People also ask

Can a class inherit from a template class?

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 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.

How do I access template classes?

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.

What is Typename C++?

" 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.


1 Answers

It's often used to realize static polymorphism.

Use cases are:

  • Policy-based design
  • Curiously recurring template pattern
  • Barton–Nackman trick

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.

like image 73
hansmaad Avatar answered Sep 17 '22 20:09

hansmaad