有时我们会用到函数重载,来应对函数功能一样但输入的参数的类型不一样的,这可以解决函数不同数据类型的影响,但是,函数重载还是要再写一遍不同数据对应的函数体。列如一个简单的求和函数,函数功能都是返回两个数之和,函数重载需要对于输入的形参的不同类型定义函数体。
#include<iostream>
using namespace std;
int sum(int x, int y) {
return x + y;
}
double sum(double x, double y) {
return x + y;
}
int main() {
int a = 3, b = 5;
cout << sum(a, b) << endl;
double c = 2.34, d = 9.13;
cout << sum(c, d) << endl;
}
而且当数据类型不止两个,而是更多个时,就会很繁琐。为了解决这个问题,便引进了函数模板。我们只需要对函数模板编写一次,然后基于调用函数时的参数类型,C++编译器将自动生产对应的函数来处理该类型的数据。函数模板就好比一个未知参数x,它的取值便是不同的数据类型,比如,int,double,char,string....使用时就像如果数据的类型为int时,即x为int,输入数据为double类型时,x便为double。
定义形式:
template<模板参数表> //参数表使用的标识符时typename(使用class一样)
类型表 函数名(参数表){
函数体
}
列如:
template<typename T>
T sum(T x,T y){
return x+y;
}
便可用这个函数模板代替上述的函数重载。
#include<iostream>
using namespace std;
template<class T>
T sum(T x, T y) {
return x + y;
}
int main() {
int a = 3, b = 5;
cout << sum(a, b) << endl;
double c = 2.34, d = 9.13;
cout << sum(c, d) << endl;
}
调用函数时,如果参数为int,则T便会替换成int,这一过程也叫函数模板的示例化。
示例:
#include<iostream>
#include<string>
using namespace std;
template<class T>
void swap(T *x, T *y) {
T temp;
temp = x;
x = y;
y = temp;
}
int main() {
int a = 3, b = 5;
swap(a, b);
cout << "a:" << a <<" "<< "b:" << b << endl;
double c = 2.34, d = 9.13;
swap(c, d);
cout << "c:" << c <<" "<< "d:" << d << endl;
char s1 = 'b', s2 = 'd';
swap(s1, s2);
cout << "s1:" << s1 << " " << "s2:" << s2 << endl;
string str1 = "you", str2 = "he";
swap(str1, str2);
cout << "str1:" << str1 << " " << "str2:" << str2 << endl;
}
结果: