一个常见的函数模板训练是写一个交换函数
其形式如下:
#include<iostream>
using namespace std;
template<typename T>
void Swap(T &a, T &b);
int main()
{
float a = 1.0;
float b = 2.0;
int c = 3;
int d = 4;
cout << "a=" << a << " b=" << b << endl;
cout << "c=" << c << " d=" << d << endl;
Swap(a, b);
Swap(c, d);
cout << "a=" << a << " b=" << b << endl;
cout << "c=" << c << " d=" << d << endl;
}
template<typename T>
void Swap(T &a, T &b)
{
T temp;
temp = a;
a = b;
b = temp;
}
这里有一些需要注意的点
第一个是template<typename T>在函数声明以及函数本体之前都需要加上
第二个是不要使用swap(小写s),如果你使用的是std命名空间,其与std::swap重名,会导致编译错误
当然你也可以不使用std命名空间