16.4.5.Member Templates
Any class (templateor otherwise) may have a member that is itself a class or function template.Suchmembers are referred to as member templates . Member templates may not bevirtual.
The problem is that the copy constructor and assignmentoperator fix both the container and element type. We'd like to define aconstructor and an assignmember that allow both the container and element typeto vary. When we need a parameter type to vary, we need to define a functiontemplate. In this case, we'll define the constructor and assignmember to take apair of iterators that denote a range in some other sequence. These functionswill have a single template type parameter that represents an iterator type.
Defininga Member Template
A template memberdeclaration looks like the declaration of any template:
template<class Type> class Queue {
public:
//construct a Queue from a pair of iterators on some sequence
template<class It>
Queue(Itbeg, It end):
head(0),tail(0) { copy_elems(beg, end); }
//replace current Queue by contentsdelimited by a pair of iterators
template<class Iter> void assign(Iter, Iter);
//rest of Queue class as before
private:
//version of copy to be used by assign to copy elements from iterator range
template<class Iter> void copy_elems(Iter, Iter);
};
The member declaration starts with its own templateparameter list. The constructor and assign member each have a single templatetype parameter. These functions use that type parameter as the type for theirfunction parameters, which are iterators denoting a range of elements to copy.
Defininga Member Template Outside the Class
When we define a member template outside the scope of aclass template, we must include both template parameter lists:
template<class T> template <class Iter>
voidQueue<T>::assign(Iter beg, Iter end)
{
destroy();// remove existing elements in this Queue
copy_elems(beg,end); // copy elements from the input range
}
When a membertemplate is a member of a class template, then its definition must include the class-templateparameters as well as its own template parameters. The class-template parameter listcomes first, followed by the member's own template parameter list.
MemberTemplates Obey Normal Access Control
MemberTemplates and Instantiation
Like any othermember, a member template is instantiated only when it is used in a program.