一.基本
以下的模版類型關鍵字class在新C++標準中建議使用typename代替.
1.1通用函數
template <class Ttype> re-type func-name(parameter list)
{
//body of funtion
}
例如:
template <class X> void swap(X &a,X &b)
{
X temp;
temp = a;
a = b;
b = temp;
}
#include <iostream>
using namespace std;
int main()
{
int i=10, j=20;
swap(i, j);
cout<<"swapped i, j:"<<i<<j<<'\n';
}
1.2通用類
template <class Ttype> class class-name
{
//body of class
}
例如:
#include <iostream>
using namespace std;
const int SIZE = 10;
template <class StackType> class stack
{
StackType stack[SIZE];
int tos; //棧頂索引
public:
stack() { tos = 0;}
void push(StackType ob)
{
if(tos==SIZE)
{
cout<<"stack is full.\n";
return;
}
stack[tos]=ob;
tos++;
}
StackType pop()
{
if(tos==0)
{
cout<<"stack is empty.\n");
return 0;
}
tos--;
return stack[tos];
}
}
int main()
{
stack<char> s1;
s1.push('a');
s1.push('b');
while(s1.tos)
{
cout<<"pop s1:"<<s1.pop()<<'\n';
}
}
本質上,我認為模版實現了通用邏輯的定義,使演算法獨立於資料類型(由於實際程式一定要先給出資料類型,所以編譯器需要先解析模版,類似於宏命令).如上面的棧類,實際可能有整型棧或浮點型棧等.如果不使用模版,我們需要針對每個類型編一個棧類,其實操作又是完全一樣.順便說一下:STL就是一批高手精心設計的模版.
二.提高
2.1多類型模版
模版類型可以有多個,如:
template <typename OrgType, typename DesType> DesType covent(OrgType org)
{
return (DesType)org;
}
2.2重載
同類等類似,模版也可以重載.如:定義同名的函數重載函數模版或定義另一個同名但類型定義數不同的模版.
template<> void swap<int>(int &a, int &b)
{
int temp;
temp = a;
a =b ;
b = temp;
}
2.3預設類型
template <class X=int> class myclass
{
//body of class
}
2.4使用無型別參數
template <class Stype, int size> class stack
{
Stype stackBuffer[size];
... ...
}
調用時:
stack<int , 20> intStack;
2.5typenaem和export關鍵字
typename 通知編譯器模版聲明中使用的名字是類型名,而不是對象名,前面的模版類型關鍵字class可以用它代替.
export用在template聲明之前,使其它檔案只通過指定模版聲明而不是全部複製來使用其它檔案中定義的模版.