在C++中有“template” 关键字,这个类似于java里面所讲的范型,而在C++里面我们称为模板。在C++中,能够很好的学好这个关键字得花上很多时间。市场上也有一些书就是讲模板编程的。
有时候,我们会遇到这种或类似的情况,要写一个函数,交换两个数的值,但是这两个数的类型不知道,可能是char / int / float
那么我们可以这样:
void swap(char& a,char& b)
{
//........
}
void swap(int& a,int& b)
{
//...
}
void swap(float&a ,float&b)
{
//....
}
代码好多,如果使用模板的话就简单多了。
template<class Type>
void swap(Type& a,Type&b)
{
Type temp;
temp = a;
a = b;
b = temp;
}
有时候,我们对特定的类型要进行特定的操作,与一般类型的操作不一样,这时候,我们得使用特化(关于特化的概念google吧)。
//我们要对char类型进行独特操作,如果不是大写字母就什么都不做
template<>
void swap(char& a,char& b)
{
if(a>'A' && a<'Z' && b>'A' && b<'Z')
{
char temp = a;
a = b;
b = temp;
}
}