//the template definition goes in a separately-compiled source fileexporttemplate<typename Type>
Type sum(Type t1, Type t2)//对于类模板而言,应该在类的实现文件中使用export,因为如果在头文件中则可能头文件include多次,多个export//class template header goes in shared header filetemplate<classType>classQueue{...};//Queue.cc implementation file declares Queue as exportedexporttemplate<classType>classQueue;#include"Queue.h"//Queue member definitions
类模板中的友元声明
普通非模板类或者函数的友元声明,将友元关系授予明确指定的类或函数
template<classType>classBar{//Grants access to ordinary, nontemplate class and functionfriendclassFooBar;friendvoidfcn();//...}
类模板或函数模板的友元声明,授予对友元所有实例的访问权
template<classType>classBar{//grants access to Foo1 or templ_fcn1 parameterized by any typetemplate<classT>friendclassFoo1;template<classT>friendvoidtempl_fnc1(const T&);//lll}
只授予对类模板或者函数模板的特定实例的访问权的友元声明
template<classT>classFoo2;template<classT>voidtempl_fcn2(const T&);template<classType>classBar{//grants access to a single specific instance parameterized by char*friendclassFoo2<char*>;friendvoid templ_fcn2<char*>(char*const&);//...}
类模板的static成员
用一个推导结果的实例的共享static,不同推导结果的不共享static,会存在另一个static
函数模板特化
特化与通用是相对的,特化就是通用的模板定义不能够再适用,为某些特殊的类型特化一个模板定义
如下代码,const char*类型的模板不能够再使用通用的大于号,小于号来比较,所以需要特化
//special version of compare to handle C-style character stringstemplate<>int compare<constchar*>(constchar*const&v1,constchar*const&v2){returnstrcmp(v1, v2);}constchar*cp1 ="world",*cp2 ="hi",int i1, i2;compare(cp1, cp2);//call the specializationcompare(i1, i2);//call the generic version instantiated with int
template<classT1,classT2>classsome_template{//...};//partial specialization:fixes T2 as int and allows T1 to varytemplate<classT1>classsome_template<T1,int>{//....};