#include <iostream>
template<typename T>
void myswap(T &a, T &b)
{
T tmp = a;
a = b;
b = tmp;
}
int main()
{
using namespace std;
int a = 1;
int b = 2;
myswap(a, b);
cout << "a " << a << endl;
cout << "b " << b << endl;
float c = 4;
float d = 5;
myswap<float>(c, d);
cout << "c " << c << endl;
cout << "d " << d << endl;
return 0;
}
$ ./a.out
a 2
b 1
c 5
d 4
函数模板有两种方式:自动类型推导、显示类型指定
模板的目的:提高复用性、将类型参数化