函数模板允许以任意类型的方式来定义函数。
例如,可以建立这样一个交换模板:
template <typename AnyType>
void Swap(AnyType &a, AnyType &b)
{
AnyType temp;
temp = a;
a = b;
b = temp;
}
第一行指出,要建立一个模板,并将类型命名为AnyType。关键字template和typename是必需的,除非可以使用关键字class代替typename。另外,必须使用尖括号。类型名可以任意选择,只要遵守C++命名规则即可。余下的代码描述了交换两个AnyType值的算法。
模板并不创建任何函数,而只是告诉编译器如何定义函数。
//funtemp.cpp---using a function template
#include <iostream>
using namespace std;
//function template prototype
template <typename T>
void Swap(T &a, T &b);
int main()
{
int i = 10;
int j = 20;
cout << "i, j = " << i << ", " << j << ".\n";
cout << "Using compiler-generated int swapper:\n";
Swap(i, j); //generated void Swap(int &, int &)
cout << "Now i, j = " << i << ", " << j << ".\n";
double x = 24.5;
double y = 81.7;
cout << "x, y = " << x << ", " << y << ".\n";
cout << "Using compiler-generated double swapper:\n";
Swap(x, y); //generated void Swap(double &, double &)
cout << "Now x, y = " << x << ", " << y << ".\n";
return 0;
}
//function template definition
template <typename T> // or class T
void Swap(T &a, T &b)
{
T temp;
temp = a;
a = b;
b = temp;
}
运行结果:
i, j = 10, 20.
Using compiler-generated int swapper:
Now i, j = 20, 10.
x, y = 24.5, 81.7.
Using compiler-generated double swapper:
Now x, y = 81.7, 24.5.
注意,函数模板并不能缩短可执行程序。对于上面的程序,最终仍将由两个独立的函数定义,就像以手工方式定义了这些函数一样。最终的代码不包含任何模板,而只包含了为程序生成的实际函数。使用模板的好处是,它使生成多个函数定义更简单,更可靠。
更常见的情形是,将模板放在头文件中,并在需要使用模板的文件中包含头文件。