類模板:類是對象的抽象,而類模板又是類的抽象,可以用模板定義出具體類(模板類)。
模板類:就是用模板定義出的具體類。
我們知道c++的多態有兩種,一是運行時的多態,也就是虛函數產生多態;二就是編譯時的多態,它就是由類模板產生的多態。
例子:
#include <iostream>
/// 一個類模板
template <typename T> // typename 也可以用 class
class Base
{
public:
void PrintTypeName() // 打印出 T 的類型
{
std::cout << typeid(T).name() << std::endl;
}
};
typedef Base<int> IntBase; // 一個模板類
typedef Base<char> CharBase; // 另一個模板類
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;
}