On Oct 4, 3:47 am, Gary Nastrasio <noem...@please.comwrote:
I'm currently reading Andrei Alexandrescu's book "Modern C++ Design" and
I'm a bit confused by one bit of template syntax in chapter 1.
Here is a code example:
template <class CreationPolicy>
class WidgetManager : public Creation Policy {...}
// Create an instance of WidgetManager which managers type Widget
WidgetManager< OpNewCreator<Widget MyWidgetMgr;
Basically the above creates a WidgetManager that handles creating new
Widgets - I completely understand this code. Since it's obvious a
WidgetManager will create type Widget, he says this code is better:
template <template <classclass CreationPolicy>
class WidgetManager : public CreationPolicy<Widget{...}
// Create an instance of WidgetManager which managers type Widget
WidgetManager<OpNewCreatorMyWidgetMgr;
I'm very confused by the line "template <template <classclass
CreationPolicy>". What exactly is going on in here?
Thanks!
Following is an extract of the mail i wrote to my team explaining the
template template parameter...Hope it helps...
I want you to write a declaration for a template class stack into
which i can push any data type and i can use any of the standard
library containers to implement the stack.
To put it simply,i want to write code as follows
Stack<int,std::vectormystack;
mystack.push(0);
mystack.push(19);
The immediate solution that occurs in our mind is to use
template.Correct!!!.But our problem is how to represent the
second parameter for the template
i.e
template <class T,????class Stack{
};
What shall i write in the place of ????.Lets try this one,
template<class T,class Contclass Stack {
Cont Container;
};
This is fine, but just one limitation.To use the above template i have
to write
Stack<int,vector<int mystack.
I had to repeat the int twice in my declaration and i am lazy enough
to resent that. Equivalently , I could have left out the first
template argument altogether.
To achieve this we need to use "template template parameter".i.e for a
template parameter we pass another template.
The above template class can be re-written as
template <class T, template < typename U class Cont class Stack{
Cont<TContainer;
};
or since we did not use U anywhere we can remove it from the
definition
template <class T, template < typename class Cont class Stack{
Cont<TContainer;
};
And here we are, we used template template parameter to pass a
template itself to a template class and
we also provided the user a very convenient form to represent his
data.
Best Regards,
Senthil