模板分为函数模板和类模板
函数模板:是一种抽象函数定义,它代表一类同构函数。
类模板:是一种更高层次的抽象的类定义。
函数模板的特化:当函数模板需要对某些类型进行特化处理,称为函数模板的特化。
类模板的特化:当类模板内需要对某些类型进行特别处理时,使用类模板的特化。
// 泛型编程.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
//函数模板
template<class T>
bool IsEqual(T t1,T t2){
return t1==t2;
}
template<> //函数模板特化
bool IsEqual(char *t1,char *t2){
return strcmp(t1,t2)==0;
}
//类模板
template<class T>
class compare{
public:
bool IsEqual(T t1,T t2){
return t1==t2;
}
};
//类模板的特化
template<>
class compare<char*>{
public:
bool IsEqual(char *t1,char *t2){
return strcmp(t1,t2)==0;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
char str1[]="abc";
char str2[]="abc";
cout<<"函数模板和函数模板特化"<<endl;
cout<<IsEqual(1,1)<<endl;
cout<<IsEqual(str1,str2)<<endl;
compare<int> c1;
compare<char*> c2;
cout<<"类模板和类模板特化"<<endl;
cout<<c1.IsEqual(1,1)<<endl;
cout<<c2.IsEqual(str1,str2)<<endl;
getchar();
return 0;
}