1. Format:template< template parameter table > (parameters can define default values directly)
Class name
{ ...};
Its member functions can be defined outside the class.
eg
1Template <classTNO,classTscore=int,intnum=Ten>2 classS3 {4 Private:5 TNO Sid[num];6 Public:7 intBel (Tscore ascore);8 voidsort ();9 };TenTemplate <classTNO,classTscore,intNum> One intS <TNO,TScore,num>:: Bel (Tscore ascore) A { - return 0; - } theTemplate <classTNO,classTscore,intNum> - voidS <TNO,TScore,num>:: Sort () - { - returnsid[0]; +}View Code
2. The implementation of the Stack class template:
1#include <iostream>2 using namespacestd;3 4Template <classT>5 classStack6 {7 Private:8 intsize;9 inttop;Tent*space; One Public: AStack (int=Ten); -~Stack () - { the delete []space; - } - BOOLPushConstt&); - T pop (); + BOOLIsEmpty ()Const - { + returntop==size; A } at BOOLIsfull ()Const - { - returntop==0; - } - }; -Template <classT> inStack <t>::stack (intsize) - { to This->size=size; +Space=NewT[size]; -top=size; the } *Template <classT> $ BOOLStack<t>::p Ush (Constt&Element)Panax Notoginseng { - if(!isfull ()) the { +space[--top]=element; A return true; the } + return false; - } $Template <classT> $T stack<t>::p op () - { - returnspace[top++]; the } - intMain ()Wuyi { thestack<Char> S1 (4); -S1.push ('x'); WuS1.push ('y'); -S1.push ('Z'); AboutS1.push ('u'); $S1.push ('v'); - while(!S1. IsEmpty ()) -Cout<<s1.pop () <<Endl; - return 0; A}View Code
Use of class templates