函数模版:
函数模版是通用的函数描述,也就是说,它们使用通用类型来定时函数,其中的通用类型可用具体的类型替换。通过将类型作为参数传递给模版,可使编译器生成该类型的函数。写个小例子如下:
1 #include <iostream>
2 using namespace std;
3
4 // function template prototype
5 template <class Any>
6 void Swap(Any &a, Any &b);
7
8 int main()
9 {
10 int i = 10;
11 int j = 20;
12 cout << "i, j = " << i << ", " << j << ".\n";
13 cout << "Using complier-generated int Swap:\n";
14 Swap(i, j);
15 cout << "i, j = " << i << ", " << j << ".\n";
16
17 double a = 23.12;
18 double b = 3.14;
19 cout << "a, b = " << a << ", " << b << ".\n";
20 cout << "Using complier-generated double Swap:\n";
21 Swap(a, b);
22 cout << "a, b = " << a << ", " << b << ".\n";
23
24 return 0;
25 }
26
27 template <class Any>
28 void Swap(Any &a, Any &b)
29 {
30 Any temp = a;
31 a = b;
32 b = temp;
33 }
~
运行效果如下:
谢谢!