Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance from a template c++

I have a question about a code that I have recently took in my hands. I just want to know if in C++ templates paradigm it is correct or useful to do the following inheritance (just 3 classes as an example):


template< class I, class P, class D, unsigned int ID = 0 >
class PathFilter : public Filter< I, P, 1 >
{
...
}

template< class I, class A, unsigned int N = 1 >
class Filter : public Algorithm< I, A >
{
...
}

template< class I, class A >
class Algorithm : public A //This line
{
   ...
}

My question is specifically about the inheritance in the third example. Is it useful to make it so 'generic' and not precise? It is a good choice to compromise understandable code by a more generic code?

I ask firstly because I'm not an expert in C++ templates, but also because I see this code difficult to understand using templates (usually the names of the templates say nothing about its content). Any advice?

like image 817
Ricardo A Corredor Avatar asked Nov 04 '22 14:11

Ricardo A Corredor


1 Answers

What you are doing is a mixin class (in particular, your class Algorithm is the one).

As a reference you can consult, for instance, http://en.wikipedia.org/wiki/Mixin or http://en.wikipedia.org/wiki/Composite_pattern.

Indeed you are specifying "certain functionality (specified by A) to be inherited or just reused by a subclass (i.e. Algorithm)". (cit. from the first article)

In other words, you are making yourself (or your user) free to add or change behavior to Algorithm somehow "afterwards". Your real gain is to achieve such a flexibility relying just on the compiler and not on some dynamic-binding-like mechanism (e.g. overriding of virtual functions). Your final class Algorithm<A>, in fact, is built at compile time and it is possibly as efficient as the class you would have obtained writing Algorithm<A> explicitly (i.e. explicitly including the policy A in Algorithm writing it by hand).

EDIT:

I would also suggest to give a look to this wikipedia page about policy based design ( http://en.wikipedia.org/wiki/Policy-based_design ).

There, policies names (your A) appear in a clear form, with clear names, as wisely advised by @full.stack.ex.

like image 159
Acorbe Avatar answered Nov 08 '22 06:11

Acorbe