这篇开始进入模板的学习,接下来要学习模板,各种函数模板和类模板,然后学习几个标准的类,例如string类的,然后过度到学习各种容器。
1.什么是模板
模板就是建立通用模具,大大提高代码复用性。
2.没有模板是什么样的
例如,我们来做这个小练习,交换两个数的值,例如有两个int类型交换,两个float类型交换。由于前面的知识,代码大概是这样去写。
#include <iostream>
using namespace std;
void SwapInt(int &a, int &b)
{
int tem = a;
a = b;
b = tem;
}
void SwapFloat(float &c, float &d)
{
float tem = c;
c = d;
d = tem;
}
void test01()
{
int a = 10;
int b = 20;
SwapInt(a, b);
cout << "a= " << a << endl;
cout << "b= " << b << endl;
float c = 1.1;
float d = 2.2;
SwapFloat(c, d);
cout << "c= " << c << endl;
cout << "d= " << d << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
注意上面交换传的参数是引用,不是具体的数值。
测试运行结果
结果肯定没有问题,两个数交换过来了。如果我们要继续交换两个字符,或者double类型,或者两个字符串,那么我们还需要写很多重复的代码。
3.模板简化了代码
下面用模板的思想来优化代码
#include <iostream>
using namespace std;
template <typename T>
void Swap(T &a, T &b)
{
T tem = a;
a = b;
b = tem;
}
void test01()
{
int a = 10;
int b = 20;
Swap(a, b);
cout << "a= " << a << endl;
cout << "b= " << b << endl;
float c = 1.1;
float d = 2.2;
Swap(c, d);
cout << "c= " << c << endl;
cout << "d= " << d << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
重点就在Swap()方法中,在方法定义上面一行,template <typename T>, 这是固定写法,其中template 和typename是关键字,T可以随便写成其他字母,一般习惯T表示模板的首字母。
运行结果一样,都产生了交换。写一个方法,可以适应全部类型的两个相同类型参数的值进行交换。这是一个函数模板。