直接在源文件中定義如下函數:
template<class T>
T MaxTry(T a, T b)
{
return a>b?a:b;
}; //結尾可寫分號,也可可不寫
下面調用MaxTry函數:
void CTemplate_TestDlg::OnButton1()
{
CString str = MaxTry("dahai","xiaohai");
//更完整的應該寫爲CString str = MaxTry<CString>("dahai","xiaohai");
MessageBox(str);
}
由於關鍵字class容易被誤會爲模版類型只能用一個類去實例化,因此又提供了一個沒有歧義的關鍵字typename用於聲明模版類型。關鍵字typename還可以在模版中強調某個標誌符是一個類型,如下:
template<class T>
class X
{
public:
typedef T X_type; //重定義T
typedef T* X_pointer; //重定義T*
};
Template<class T>
class Y
{
public:
typedef typename X<T>::X_type Y_type;
typedef typename X<T>::X_pointer Y_pointer;
};
二類模版
可以在頭文件中定義如下類(也可以直接定義在源文件中):
template<class T>
class DaHai
{
T a;
public:
DaHai(T n){a = n;}
T Add(T n){return n+a;}
}; //結尾必須寫分號
也可以在源文件中實現函數:
template<class T>
T DaHai<T>::Add(T n)
{
return a+n;
}
注:函數模版和類模版的聲明和定義代碼,一般都編寫在.h頭文件中,以免由於未實例化而提示編譯鏈接錯誤。
三模版完全特化
函數模版的完全特化是在函數模版定義出來後,再用關鍵字“template<>”開頭,給出特定類型下的函數模版定義。
template<class T>
void func(T a)
{
Printf(“hello/n”);
}
template<> void func<int>(int a)
{
Prientf(“hello there/n”);
}
int main(void)
{
func(2); //打印hello there
func(‘y’); //打印 hello
return 0;
}