模板静态成员 template<typename T> class B { public: static int m_data; }; int B<int>::m_data = 1; int B<char>::m_data = 2; 模板偏特化 //模板函数偏特化 //一般化 template<typename I , typename O> class D { public: D(){cout<<"I,O"<<endl;}; }; //特殊化 template<typename I> class D<I*,I*> { public: D(){cout<<"I*,I*"<<endl;}; }; //特殊化 template<typename I> class D<const I*,I> { public: D(){cout<<"const I* ,I"<<endl;}; }; 函数特化 //函数特化 class alloc {}; template<typename T,typename Alloc =alloc> class vector { public: void swap(vector<T,Alloc>&){cout<<"swap()"<<endl;}; }; template<typename T,typename Alloc> inline void swap(vector<T,Alloc>& x ,vector<T,Alloc>& y) { x.swap(y); }; int main(void) { vector<int> x,y; swap(x,y); } 模板成员 class alloc {}; //模板成员 template<class T, class Alloc = alloc> class V { public: typedef T value_type; typedef value_type* iterator; template<class I> void Insert(iterator postion , I first , I last) { cout<<"insert()"<<endl; } }; int main(void) { int ia[5] ={0,1,2,3,4}; V<int> x; V<int>::iterator iter; x.Insert(iter,ia,ia+5); } 模板参数根据前一个模板参数而设定默认值 template<class T,class Alloc = alloc, size_t buffer =0> class deque { public: deque(){cout<<"deque"<<endl;}; }; template<class T,class S = deque<T> > class stack { public: stack(){cout<<"stack"<<endl;}; private: S c; }; int main(void) { stack<int> x; } 模板类符号重载 //在上面stack基础上加入 //注意重载写法 friend bool operator == <>(const stack& ,const stack&); friend bool operator < <>(const stack& ,const stack&); //当然也可以写成 friend bool operator == <T>(const stack<T>& ,const stack<T>&); friend bool operator < <T>(const stack<T>& ,const stack<T>&); //也可以写成 friend bool operator == <T>(const stack& ,const stack&); friend bool operator < <T>(const stack& ,const stack&); //但是不可以写成 //friend bool operator == (const stack& ,const stack&); //friend bool operator < (const stack& ,const stack&); //操作符重载实现 template<class T,class S> bool operator ==(const stack<T,S>& x ,const stack<T,S>& y) { return cout<<"operator =="<<'/t'; }; template<class T,class S> bool operator <(const stack<T,S>& x ,const stack<T,S>& y) { return cout<<"operator <"<<'/t'; }; // int main(void) { stack<int> x; stack<int> y; cout<<(x==y)<<endl; cout<<(x < y)<<endl; }