类模板
什么是类模板?
模板的目的就是为了淡化数据类型的要求,作出通用数据类型的模板。类中的成员变量和成员函数都牵涉到了数据类型。
在成员函数、成员变量以及基类中包含有类型参数的类称为类模板。
和函数模板一样,类模板只是一个模板,并不是真正的类。
形式:template<class T1, class T2, … ,class Tn>
class className
{ … };
1、选择性实例化
没用调用的方法不会进行实例化。
2、模板的特例化
template<typename E>
Node* Find(E val) //模板版本
{
std::cout << "template<typename E> Node* CLink<T>::Find(E)" << std::endl;
Node* pCur = phead->pnext;
Node* prt = NULL;
while (pCur != NULL)
{
if (pCur->mdata == val)
{
prt = pCur;
break;
}
}
return prt;
}
template<>
Node* Find(char* val) //特例化的版本
{
std::cout << "template<> Node* CLink<T>::Find(char*)" << std::endl;
Node* pCur = phead->pnext;
Node* prt = NULL;
while (pCur != NULL)
{
if (strcmp(pCur->mdata,val) == 0)
{
prt = pCur;
break;
}
}
return prt;
}
完整代码
template<typename T>
class CLink
{
public:
CLink()
{
std::cout << "template<typename T> class CLink" << std::endl;
phead = new Node();
}
CLink(const CLink<T>& rhs)
{
std::cout << "CLink(const CLink<T>& rhs)" << std::endl;
phead = new Node();
Node* ptail = phead;
Node* pCur = rhs.phead->pnext;
while (pCur != NULL)
{
Node* pnewnode = new Node(pCur->mdata);
ptail->pnext = pnewnode;
pCur = pCur->pnext;
ptail = ptail->pnext;
}
}
template<typename E>
CLink(const CLink<E>& rhs)// 退化成构造函数
{
std::cout << "template<typename E> CLink(const CLink<E>& rhs)" << std::endl;
phead = new Node();
Node* ptail = phead;
CLink<E>::Node* pCur = rhs.phead->pnext;
while (pCur != NULL)
{
Node* pnewnode = new Node(pCur->mdata);
ptail->pnext = pnewnode;
pCur = pCur->pnext;
ptail = ptail->pnext;
}
}
~CLink()
{
Node* pCur = phead;
Node* pNext = pCur;
while (pCur != NULL)
{
pNext = pCur->pnext;
delete pCur;
pCur = pNext;
}
phead = NULL;
}
bool InsertTail(T val)
{
Node* pnewnode = new Node(val);
Node* ptail = phead;
while (ptail->pnext != NULL)
{
ptail = ptail->pnext;
}
ptail->pnext = pnewnode;
return true;
}
void Show()
{
Node* pCur = phead->pnext;
while (pCur != NULL)
{
std::cout << pCur->mdata << " ";
pCur = pCur->pnext;
}
std::cout << std::endl;
}
class Node;//前置声明
Node* Find(T val)//普通方法
{
std::cout << "Node* CLink<T>::Find(T)" << std::endl;
Node* pCur = phead->pnext;
Node* prt = NULL;
while (pCur != NULL)
{
if (pCur->mdata == val)
{
prt = pCur;
break;
}
}
return prt;
}
template<typename E>
Node* Find(E val) //模板版本
{
std::cout << "template<typename E> Node* CLink<T>::Find(E)" << std::endl;
Node* pCur = phead->pnext;
Node* prt = NULL;
while (pCur != NULL)
{
if (pCur->mdata == val)
{
prt = pCur;
break;
}
}
return prt;
}
template<>
Node* Find(char* val) //特例化的版本
{
std::cout << "template<> Node* CLink<T>::Find(char*)" << std::endl;
Node* pCur = phead->pnext;
Node* prt = NULL;
while (pCur != NULL)
{
if (strcmp(pCur->mdata,val) == 0)
{
prt = pCur;
break;
}
}
return prt;
}
private:
class Node
{
public:
Node(T val = T()) :mdata(val), pnext(NULL){}
public:
T mdata;
Node* pnext;
};
friend class CLink;
Node* phead;
};
int main()
{
CLink<int> ilink;//CLink<int>
CLink<double> dlink(ilink);
CLink<int> ilink1(ilink);
return 0;
}