函数模版:
定义函数模版的语法格式:
template
template
T add(T a, T b)
{
return a + b;
}
函数模版不会减少可执行程序的大小,因为编译器会根据调用时的参数类型进行相应的实例化,就是用类型参数替换模版中的模版参数,生成具体类型的函数,模版是为了减少开发的工作量,进而提高可维护性。
实例化可分为隐式实例化与显式实例化。
①隐式实例化
隐式实例化是根据函数调用时传入的参数的数据类型确定模板形参T的类型,模板形参的类型是隐式确定的。
#include
using namespace std;
template
T add(T a,T b)
{
return a + b;
}
int main()
{
cout << add(3,5) << endl;
cout << add(2.72,3.24) << endl;
return 0;
}
显式实例化
隐式实例化不能为同一个模版形参指定两种不同的类型,如add(1,1,2),函数形参的类型不一致,编译器便容易报错。这就需要显示实例化解决类型不一致的问题,显式实例化需要指定函数模版中的数据类型,语法格式就如下面。
template 函数返回值类型 函数名<实例化的类型>(参数列表);
由于C++编译器不断的完善,模板实例化的显式声明可以省略,在调用时用<>显式指定要实例化的类型即可。
cout << add<double>(2.72, 5) << endl;//显式实例化,在模板后面加上<具体类型>
#include
using namespace std;
template
T tmax(T a,T b)
{
return a > b ? a : b;
}
//显式具体化
template<>
const char* tmax(const char* a,const char* b)
{
if(strcmp(a,b) > 0)
return a;
return b;
}
int main()
{
cout << tmax(3,5) << endl;
cout << tmax(3.14,2.72) << endl;
const char* s1 = "Good";
const char* s2 = "Hello";
cout << tmax(s1,s2) << endl;
return 0;
}
注意:如果函数有多个原型,则编译器在选择函数调用时,非模板函数优先于模板函数,显式实例化模板优先于函数模板。
函数模版也支持重载
#include
using namespace std;
//这里就是非模版函数
int tmax(const int& a,const int& b){
return a > b ? a : b;
}
template //定义求两个任意类型数据的最大值
T tmax(const T& t1,const T& t2){
return t1 > t2 ? t1 : t2;
}
template //定义求三个任意类型数据的最大值
T tmax(const T& t1,const T& t2,const T& t3){
return tmax(tmax(t1,t2),t3);
}
int main()
{
cout << tmax(1,2) << endl;
cout << tmax(1,2,3) << endl;
cout << tmax('a','e') << endl;
cout << tmax(6,3.2) << endl;
return 0;
}
最后的模版题,包含append,insert,remove,[],clear