目录
函数模板基本概念
C++新增的一项特性
使用泛型来定义函数,泛型可以用具体的类型int 和 double 替换
又称为通用编程
比如int 全部替换为 double,那么它就派上用场了!
一个交换的函数模板
template <typename AnyType>
void Swap(AnyType &a, AnyType &b)
{
AnyType temp;
temp = a;
a = b;
b = temp;
}
C++98以前使用的是class
template <class AnyType>
void Swap(AnyType &a, AnyType &b)
{
AnyType temp;
temp = a;
a = b;
b = temp;
}
class 和 typename效果一样,有很多代码还是用class,所以不用吃惊
程序示例
//8.1 functemp.cpp -- 使用函数模板
#include<iostream>
//函数模板声明
template <typename T> //or class T
void Swap(T &a, T &b);
int main()
{
using namespace std;
int i = 10;
int j = 20;
cout << "i, j = " << i << ", " << j << ".\n"<<endl;
cout << "使用模板int:\n";
Swap(i, j);//这里生成了Swap(int &, int &)
cout << "Now i, j = " << i << ", " << j << ".\n" << endl;
double x = 24.5;
double y = 81.7;
cout << "x, y = " << x << ", " << y << ".\n" << endl;
cout << "使用模板double:\n";
Swap(x, y);//生成void Swap(double &, double &)
cout << "Now x, y = " << x << ", " << y << ".\n" << endl;
return 0;
}
//模板定义
template <typename T> //or class T
void Swap(T &a, T &b)
{
T temp;
temp = a;
a = b;
b = temp;
}
(8.5,程序8.11)