views:

341

answers:

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?

A: 

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

Klaim
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.
Phil Nash
+1  A: 

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
+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.
Phil Nash
A: 

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
Scott's article is about CRTP. This is about the "inverse" of CRTP (ie `template<class T>struct Derived : T{};` vs `struct Derived : public Base<Derived>{};`)
Phil Nash
+1  A: 

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
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.
Phil Nash
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.
+1  A: 

This is a mixin

Itay
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.
Phil Nash
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<ConcreteClass> MyNewType;
Itay
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.
Phil Nash
Between you and Jonnii I'm convinced this is still a mixin. Thanks for your comments
Phil Nash
+2  A: 

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.
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 ;-)
Phil Nash
+1  A: 

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
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
Phil Nash
+1  A: 

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