8

There's a less common C++ idiom that I've used to good effect a few times in the past. I just can't seem to remember if it has a generally used name to describe it.

It's somewhat related to mixins, CRTP and type-erasure, but is not specifically any of those things.

The problem is found when you want to add some implementation to a class, but you don't want to put it in the class, or any class it derives from. One reason for this might be that the class could be part of an inheritance hierarchy where the implementation should only occur once.

Setting aside, for the the moment, issues such as whether a hierarchy should have concrete non-leaf classes, or whether virtual inheritance may be an option in some cases, I know that one solution to provide the implementation in a template class that derives from its template parameter. This then allows you to use the template when you create an instance, but then only ever use the object by pointer or reference to one of its bases (that's where the type erasure, in a loose sense, comes in).

An example might be that you have an intrusive reference count. All your classes derive from a ref count interface, but you only want the ref count itself, and the implementation of your ref count methods, to appear once, so you put them in the derived template - let's call it ImplementsRC<T>. Now you can create an instance like so:

ConcreteClass* concrete = new ImplementsRC<ConcreteClass>();

I'm glossing over things like forwarding constructors formed of multiple templated overloads etc.

So, hopefully I've made it clear what the idiom is. Now back to my question - is there an accepted, or at least generally used, name for this idiom?

philsquared
  • 22,403
  • 12
  • 69
  • 98
  • Seems sort of related to the Visitor pattern or External Polymorphism...but not quite. – Drew Hall Dec 17 '09 at 11:55
  • I don't really see how its related to either of those patterns - care to elaborate? – philsquared Dec 17 '09 at 12:00
  • Actually it doesn't even use CRTP. I mentioned CRTP here because it seems like the reverse of CRTP. – philsquared Dec 17 '09 at 12:30
  • @Andreas - With CRTP it's the base class that is a template, where the template argument is the type of the derived class. With the idiom I described, its the derived class that's a template where the template argument is the type of the base class. – philsquared Dec 17 '09 at 12:32
  • Isn't `ImplementsRC` CRTP? Doesn't `ImplementsRC` inherit `ConcreteClass`? – Andreas Brinck Dec 17 '09 at 12:33
  • @Phil Aha, (I wrote my comment before I saw your answer) – Andreas Brinck Dec 17 '09 at 12:34
  • @Phil You mean: `struct base : derived` – Andreas Brinck Dec 17 '09 at 12:36
  • @Andreas - yes, that's pretty much it – philsquared Dec 17 '09 at 12:37
  • Maybe it doesn't have a name. Time to coin one. – jon hanson Dec 17 '09 at 12:40
  • 1
    Isn't it a template specific version of the bridge pattern? – Georg Fritzsche Dec 17 '09 at 12:42
  • @gf I hadn't really thought about it in Bridge terms. I can certainly see elements of Bridge in there, but I'm not sure I'd really say that's what it is. Either way it's the technique of *implementing* this that is interesting (at least to me). To put it another way - what would you call the class that does the work (I called it ImplementsRC in the specific example, but if you wanted to generalise...)? I don't think you'd call it Bridge. – philsquared Dec 17 '09 at 13:24
  • There is an important difference in wether you add to the functionality functionality of `ConcreteClass` or provide completely unrelated functionality, i don't think you can generalize that away just because the syntax looks the same. – Georg Fritzsche Dec 17 '09 at 14:30
  • @gf What I'm actually doing in this case is providing the implementation in the derived class for some methods of an interface that the base class derives from. To be generic the implementation must be orthogonal to the base class by definition (hence the ref count example). – philsquared Dec 17 '09 at 15:24
  • Ok, i seem to have missed the orthogonality. – Georg Fritzsche Dec 17 '09 at 19:01

9 Answers9

3

It is an interesting idea. However I am not going to give you the name of an already established pattern here, on the very contrary I am going to explain (somewhat) why I don't think it already has one.

What does it do?

It is a very nice way to avoid the dread diamond inheritance.

Since there is some confusion apparently as to the purpose of the method, let me elaborate why I think this is its purpose:

class RefCounted
{
  virtual void addReference() = 0;
  virtual void removeReference() = 0;
};

class B: public RefCounted {};
class C: public RefCounted {};

class Diamond: public B, public C {};

Now, we here have a problem. If we put the implementation of RefCounted right in this class, it becomes a base-class instead of an interface, and thus we have to use virtual-inheritance or the data members will be duplicated (present in both B and C).

The idea is thus to defer the implementation to the last moment.

Advantages:

  • No need to try to second-guess the use of B or C: virtual inheritance is unnecessary there.
  • The compiler will nicely remind you if you forget to add the implementation, so no need to worry about that.

Inconvenient:

  • Put the burden on the client: you'd better have a factory to create your objects, especially since one object may implement various interfaces!!! Note that this might be automated with template meta-programming (more or less) or can simply been provided by the class author.

Example of providing:

// d.h
class D: public B, public C
{
public:
  typedef ImplementRC<D> concrete_type;
  static concrete_type Build(int, int); // Named Constructor idiom

private:
  D(int,int);
}; // class D

// main.cpp
D::concrete_type myD = D::Build(1,2);

So what's the name ?

I can't think of anything that exactly matches this. Bridge and Decorator have been mentionned but this is quite special, and indeed not so OO-oriented (for example it won't happen in Java since you don't have Multi-Inheritance), so I doubt the term is going to be found in the GoF's book.

Also, it's not really the CRTP because there is a kind of loop in the CRTP (base being aware of its derived class) that does not happen here > we indeed are strictly linear!

And then, it's certainly not the Pimpl idiom, which proposes to hide the implementation away from the client while using a template for the implementation just throw it to its face! (The template could use Pimpl as an internal detail though)

I humbly suggest jiti for Just In Time Implementation, which mimicks the title somehow, but is closer to the point I think, derivation here being just a tool rather than a goal.

Interesting idea anyhow.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
  • Thanks Matthieu. You certainly seem to have grasped the design. And yes it is largely a way of avoiding the diamond inheritance problem without virtual inheritance. JITI is an interesting name. Not sure if it's really better or worse than mine, although at least has a more pronounceable acronym ;-) – philsquared Dec 17 '09 at 18:47
1

I'm not sure this has a name, as gf suggested it's looks a bit like the bridge pattern. It's almost like your hooking on functionality to the base class.

I suggest a new name for this, the pimp idiom. As you're pimping your base class ;)

Andreas Brinck
  • 51,293
  • 14
  • 84
  • 114
  • +1 for suggesting the pimp idiom :-) If we did have to coin the name here I like that one. Unfortunately I'd also have to reject it as there's too much scope for confusion with the pImpl idiom ;-) wrt Bridge, see my response to gf's comments. – philsquared Dec 17 '09 at 13:26
1

Are you looking for the Decorator pattern?

Basically the decorator is an object that encloses another object and extends the functionality of certain methods. The method calls are then forwarded to the enclosed method.

Martin York
  • 257,169
  • 86
  • 333
  • 562
  • There is certainly some resonance with Decorator, just as there is some with Bridge. But Decorator is specifically a runtime thing and is intended to be alternative to a subclassing approach. Also decorator's strength is it allows you to provide numerous decorations, whereas my approach only does one at a time - although I could envisage a generalised mixin-holder template that might achieve that. Again, either way, it's an idiom level name I'm looking for - not pattern level. – philsquared Dec 17 '09 at 15:28
  • Actually, nothing prevents your idea to be applied recursively: `ConcreteClass* cc = new ImplementA< ImplementB< ConcreteClass > >();`, at the condition to derive from both `InterfaceA` and `InterfaceB`. However, the Decorator means enriching an existing functionality while in your approach the functionality does not exist before. – Matthieu M. Dec 17 '09 at 17:53
1

This is a mixin

Itay Maman
  • 30,277
  • 10
  • 88
  • 118
  • While it certainly shares some aspects of mixins I deliberately ruled that out. From the wikipedia article I linked to (feel from to contradict that - is there an authoritative definition somewhere?) it says, "a mixin is a class that provides a certain functionality to be inherited by a subclass, while not meant for instantiation". On both counts the idiom I'm talking about reverses the situation. It's the generic class that subclasses the specific class (awkward terminology there) and is meant for instantiation. Maybe the base class is the mixin, but that's not what I need the name for. – philsquared Dec 17 '09 at 15:34
  • I don't agree with the Wikipedia definition. Here's an academic work on mixins: http://www.disi.unige.it/person/LagorioG/jam. Examining the declaration: "class ExampleWithUndo = Undo extends Example {}" (at the end of the second snippet), where Undo is a mixin, seems 100% equivalent to typedef ImplementsRC MyNewType; – Itay Maman Dec 17 '09 at 16:01
  • Very interesting. That does seem to correspond more strongly. I'm not sure *I* agree with that sites use of mixin, however :-) Heir Class sounds like a more useful term, though. Thanks for the link. – philsquared Dec 17 '09 at 16:51
  • Between you and Jonnii I'm convinced this is still a mixin. Thanks for your comments – philsquared Dec 17 '09 at 20:54
1

I'd definitely consider this to be a mixin, as would Bruce Eckel (http://www.artima.com/weblogs/viewpost.jsp?thread=132988).

In my opinion one of the things that makes this a mixin is that it's still single inheritance, which is different from using MI to achieve something similar.

jonnii
  • 28,019
  • 8
  • 80
  • 108
  • Ok, I'm convinced. I'd still like to differentiate this from a "standard" MI mixin, though. I'm marking this as the accepted answer because it was the Eckel article that convinced me, but technically Itay pushed for Mixin first – philsquared Dec 17 '09 at 20:53
1

Looking at your reference counting example, you may get some joy looking into CComObject<> which is one of a few template classes that ATL contains to provide the implementation of IUnknown. It also uses policy classes to vary the behaviour. Naturally the signal-to-noise ratio trying to Google about the concept of CComObject is very low because it's so ubiquitous. This MSDN article may give you some more "keywords" to aid any searching.

http://msdn.microsoft.com/en-us/library/c43h4867(VS.80).aspx

[NB: Just to be clear - I'm not suggesting he uses CComObject, I'm suggesting it is another popular example of the same concept and therefore may have been referenced in a patterns book or article]

Chris Oldwood
  • 1,060
  • 10
  • 17
  • Thanks, Chris. I think `CComObject<>` is probably one of the first examples I saw of this idiom in use. I don't recall Microsoft ever referring to it as a named idiom, however - and a quick look at the linked article doesn't suggest anything different. – philsquared Dec 18 '09 at 16:47
0

Looks like Pimpl idiom? Maybe used in an unusual way.

Klaim
  • 67,274
  • 36
  • 133
  • 188
  • No, it's not really a pImpl. That's just for moving the guts of the implementation out for minimising dependencies - this is deferring it to a class that's only used at the point of instantiation. – philsquared Dec 17 '09 at 12:10
0

I am not sure but is it "empty member c++ optimization" ?

and such kind of behaviour is implemented using class templates and private inheritance.

It is explained in Magazine Article named "Counting Objects in C++" by Scott Meyer.

Ashish
  • 8,441
  • 12
  • 55
  • 92
  • Scott's article is about CRTP. This is about the "inverse" of CRTP (ie `templatestruct Derived : T{};` vs `struct Derived : public Base{};`) – philsquared Dec 17 '09 at 13:33
0

Answering my own question. First sign of madness? - no there were several signs before this ;-)

Anyway, it's been so long since I originally posted I'm more-or-less a different person anyway.

I've found that I've settled on the name, mixover. I've found this fits very nicely and can be considered a refinement of mixin, rather than being exclusive to the more general concept.

I've been using them a lot recently so I thought I'd come back and update this thread.

philsquared
  • 22,403
  • 12
  • 69
  • 98