模板就是建立通用的模具,大大提高复用性。
c++的另一种编程思想是泛型编程,主要利用的就是模板。
c++提供两种模板机制:函数模板和类模板。
声明:template<class T>//typename可以替换成class
函数模板
函数模板的作用:建立一个通用函数,其函数返回值类型和形参类型可以不具体制定,用一个虚拟的类型来代表。
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void swapInt(int& a,int& b) {
int tmp = a;
a = b;
b = tmp;
}
void swapFloat(float& a, float& b) {
float tmp = a;
a = b;
b = tmp;
}
int main() {
int a = 1;
int b = 2;
swapInt(a, b);
cout << "a=" << a << "\t" << "b=" << b << endl;
float c = 1.1f;
float d = 2.2f;
swapFloat(c, d);
cout << "c=" << c << "\t" << "d=" << d << endl;
system("pause");
return 0;
}
假设我们要设置所有数据类型的交换函数,那么如果按照普通的方式来写,就要写很多的函数,利用泛型就可以进行简化。
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
//模板函数
//声明一个模板,表明T是一个通用数据类型
template<typename T>
void mySwap(T& a,T& b) {
T tmp = a;
a = b;
b = tmp;
}
int main() {
int a = 1;
int b = 2;
//使用模板函数有两种方式
//1.自动类型推导
mySwap(a, b);
cout << "a=" << a << "\t" << "b=" << b << endl;
//2.显示指定类型
mySwap<int>(a, b);
cout << "a=" << a << "\t" << "b=" << b << endl;
float c = 1.1f;
float d = 2.2f;
mySwap(c, d);
cout << "c=" << c << "\t" << "d=" << d << endl;
system("pause");
return 0;
}
输出:
模板注意事项: