類模板:類是對(duì)象的抽象,而類模板又是類的抽象,可以用模板定義出具體類(模板類)。
模板類:就是用模板定義出的具體類。
我們知道c++的多態(tài)有兩種,一是運(yùn)行時(shí)的多態(tài),也就是虛函數(shù)產(chǎn)生多態(tài);二就是編譯時(shí)的多態(tài),它就是由類模板產(chǎn)生的多態(tài)。
例子:
#include <iostream>
/// 一個(gè)類模板
template <typename T> // typename 也可以用 class
class Base
{
public:
void PrintTypeName() // 打印出 T 的類型
{
std::cout << typeid(T).name() << std::endl;
}
};
typedef Base<int> IntBase; // 一個(gè)模板類
typedef Base<char> CharBase; // 另一個(gè)模板類
int main()
{
IntBase* pIntBase = new IntBase;
if (NULL != pIntBase)
{
pIntBase->PrintTypeName();
delete pIntBase;
pIntBase = NULL;
}
CharBase* pCharBase = new CharBase;
if (NULL != pCharBase)
{
pCharBase->PrintTypeName();
delete pCharBase;
pCharBase = NULL;
}
system("pause");
return 0;
}