1

In Alexandrescu's book there is a piece of code that really confuses me.

template <template <class Created> class CreationPolicy> 
class WidgetManager : public CreationPolicy<Widget> 
{ 
 ... 
};

As far as I can tell its a template class within a template. So we accept 'Created' and make it into CreationPolicy class and then publicly inheritting WidgetManager from newly created CreationPolicy class. How is that even possible? Am misinterpreting something here?

Anon
  • 1,274
  • 4
  • 17
  • 44
  • 3
    That's a [template template parameter](http://stackoverflow.com/questions/213761/what-are-some-uses-of-template-template-parameters-in-cž). – jrok Apr 07 '14 at 12:46
  • but what does `class Created` means there shouldnt it just be `class` instead? (in the link you posted theres no `Created` in the same code excerpt) – Anon Apr 07 '14 at 12:50
  • 1
    The code does compile if you declare a Widget. The inner template is specifying that CreationPolicy is itself a template class. What Alexandrescu is trying to do is decouple the creation policy (semantics) from the actual object created. Why you would want to do this in anything other than the deepest recesses of a library is a question I do not have a good answer for. – Richard Hodges Apr 07 '14 at 13:04
  • 1
    @VisViva specifying "class Created" instead of just "class" for the template template param is just for better documentation (quote: "similar to a formal argument name in a function declaration") - see f.e. http://www.informit.com/articles/article.aspx?p=376878 – wonko realtime Apr 07 '14 at 13:16

1 Answers1

1

CreationPolicy is a template class, specialised on some class Created.

WidgetManager is derived from a CreationPolicy specialised specifically for creating Widget objects (the thing that the WidgetManager is managing).

A declaration for Widget must already be avaiable to the compiler.

WidgetManager is also a template class, specialised on the CreationPolicy (which is itself a templated class).

What Alexandrescu has done is decouple the manager from the way it creates objects. He has also decoupled the creation means from the object that is being created and managed.

So you could do this:

WidgetManager<MemoryCreator> manager1 = ...;

WidgetManager<FileSystemCreator> manager2 = ...;

and then you can ask manager1 or manager2 for a Widget object without caring how they are created.

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142