The main class template stack, built using vectors, implements the functionality of the stack.
template <typename t>class Stack { Private : std :: Vector <t> elems; public : void push (T const &elem) {elems.push_back (elem); } void pop () {if (Elems.empty ()) return ; Elems.pop_back (); } T Top () const {if (Elems.empty ()) return ; return elems.back (); }}
If the template parameter is string, we need to use deque instead of vector to hold the stack element. This requires a special processing of the class template. Look at the code snippet below.
Template<>classstack<STD::string> {//template parameter is a specific stringPrivate:STD:: deque<std::string>Elems Public:voidPushSTD::string Const&elem) {elems.push_back (elem); }voidPop () {if(Elems.empty ())return; Elems.pop_back (); }STD::stringTop ()Const{if(Elems.empty ())return;returnElems.back (); }}
The instantiated template is called a special template class. In this code snippet, the special template class is only for a specific type (std::string), which is called full specificity. For full specificity, the contents of the first line of the template angle brackets should be empty. The above code completes the stack operation with Deque.
There is a complete specificity, there is a part of the special. Look at the code below.
template <typename T>class Stack<T*> {private: std::list<T*> elems;public: void push(T* &elem){ elems.push_front(elem); } //same}
The first line declares T to be a template parameter, and row 2 means that when the template parameter needs to be a pointer, the main class template is not used and the template is customized.
In general, there is a main class template:
template <typename T1,typename T2,...typename Tn>class C { ...}
A special class template should have the form:
template <typename P1,typename P2,...typename PN>class C<type1,type2,...typeN> { ...}
When the n template parameters of the main class template have the type type1,type2 ... in line 2, respectively, the compiler uses the code in the Special class template instead of the main class template to instantiate the operation.
The type2 (or any other) in line 2 can be a certain type, such as int, or a template parameter. In the latter case, you need to use the TypeName declaration in the first line type2 is a type name. For example:
template <typename T1,typename T2>//主类模板class Myclass { ...}
The following code defines a special class template to handle cases where the T2 is int:
T>class Myclass<T,int> { //T2为int ...}
The following code is used to handle the case where both T1 and T2 are pointers:
template <typename T1,typename T2>class Myclass<T1*,T2*> { ...}
Class template specificity