您的位置:首页 > 其它

函数模板和类模板的定义和使用

2016-05-29 13:42 316 查看
模板是泛型编程的基础。所谓泛型编程就是编写与类型无关的逻辑代码,是一种复用的方式。模板分为函数模板和类模板。
函数模板:建立一个通用函数,其函数类型和形参类型不具体指定,用一个虚拟的类型来代表,这个通用函数就称为函数模板。
一般形式:template<typename T>
通用函数定义
注意:关键字typename是类型名,只适用于函数体相同、函数的参数个数相同而类型不同的情况。
函数模板格式:
 template <class 形参名1, class 形参名2, class 形参名n>
返回类型 函数名(参数列表)
 {...}
模板形参的定义既可以使用class,也可以使用typename,含义是相同的。
例1:用函数模板实现求3个数中的最大者。程序:#include<iostream>
using namespace std;
template<typename T>//模板声明,T为类型参数
T max(T a, T b, T c)//定义一个通用函数,T作虚拟类型名
{
if (b > a)
{
a = b;
}
if (c > a)
{
a = c;
}
return a;
}

int main()
{
int i1 = 12, i2 = 3, i3 = 9, i;
double d1 = 56.7, d2 = -23.5, d3 = 33.6, d;
long g1 = 67854, g2 = -912456, g3 = 673456, g;
i = max(i1, i2, i3);//T被int取代
d = max(d1, d2, d3);//T被double取代
g = max(g1, g2, g3);//T被long取代
cout << "i_max=" << i << endl;
cout << "d_max=" << d << endl;
cout << "g_max=" << g << endl;
system("pause");
return 0;
}
结果:i_max=12d_max=56.7g_max=673456请按任意键继续. . .类模板:类模板是类的抽象,类是类模板的实例在类模板内定义:类模板名<实际类型名>对象名;类模板名<实际类型名>对象名(实参表);在类模板外定义成员函数:template<class 虚拟类型参数>函数类型 类模板名<虚拟类型参数>::成员函数名(函数形参表){...}如:template<class numtype>numtype Compare<numtype>::max(){return(x > y) ? x : y;}例2:声明一个类模板,利用它分别实现两个整数、浮点数和字符的比较,求出大数和小数。程序:#include<iostream>using namespace std;template<class numtype>//类模板声明,虚拟类型名为numtypeclass Compare//类模板名为Compare{public: Compare(numtype a, numtype b)//定义构造函数 { x = a; y = b; } numtype max() { return(x > y) ? x : y; } numtype min() { return(x < y) ? x : y; } private: numtype x, y;};
int main(){ Compare<int>cmpl(3, 7); cout <<cmpl.max()<<" is the Maximum of two integer numbers. "<< endl; cout << cmpl.min() << " is the Minimum of two integer numbers. " << endl<<endl; Compare<float>cmp2(3.5, 77.1); cout << cmp2.max() << " is the Maximum of two integer numbers. " << endl; cout << cmp2.min() << " is the Minimum of two integer numbers. " << endl << endl; Compare<char>cmp3('a', 'A'); cout << cmp3.max() << " is the Maximum of two integer numbers. " << endl; cout << cmp3.min() << " is the Minimum of two integer numbers. " << endl; system("pause"); return 0;}结果:7 is the Maximum of two integer numbers.3 is the Minimum of two integer numbers. 77.1 is the Maximum of two integer numbers.3.5 is the Minimum of two integer numbers. a is the Maximum of two integer numbers.A is the Minimum of two integer numbers.请按任意键继续. . .模板优缺点总结

优点:
模板复用了代码,节省资源,更快的迭代开发,C++的标准模板库(STL)因此而产生。

增强了代码的灵活性。

缺点:
模板让代码变得凌乱复杂,不易维护,编译代码时间变长。

出现模板编译错误时,错误信息非常凌乱,不易定位错误。

本文出自 “岩枭” 博客,请务必保留此出处http://yaoyaolx.blog.51cto.com/10732111/1760103
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: