I have my own array class template I would like to optionally add functionality to.
As an example of functionality, take multithreading support: in some cases, I need arrays that put #pragma omp atomic just before any update code (a compiler directive that enforces atomic behaviour, the details aren’t important). In other cases, I need arrays that don’t do this, as I know they will only be updated safely and I need to avoid the performance hit.
Intuitively it should be possible to define a class called AtomicUpdates that I can inherit from. So to define a double array with atomic updates I would say something like
class AtomicDoubleArray : public MyArray<double>, public AtomicUpdates {};
But I can’t see how you’d implement that in practice, and also this would break the principle of inherit interface, not implementation.
Can anyone enlighten me as to what I really want to do here?
Even if you don’t end up using them now mixins and policy template arguments are very useful things to understand. In this case they are very similar. First, an array with a mixin base. I have used c++0x mutex rather than openmp but you should get the idea.
Now the same class but using a policy argument approach rather than inheritance.
In this case both are very similar. The important difference is that the mixin could define some methods to be virtual and allow you to change the behaviour of array by inheriting from it. As in the following:
While there are some real cases where the mixin advantage is useful it is not that often. So when working with templates the policy approach is often the more appropriate. Policy arguments are used by the standard library in many places so there are some good examples for you to study.
As for your question about “inherit interface, not implementation.” Used carefully inheriting implementation is quite useful. Same goes for multiple inheritance. You just need to be judicious about when you use them.