函数模板类似于函数重载。
函数模板的一般定义形式如下:
template<类型形式参数表> //模板前缀
返回类型 函数名(形式参数表)
{
//函数体
}
程序如下:
#include<iostream.h>
template<class T> //T代表某种数据类型,也可以用template<typename T>
void swap(T &x1, T &x2)
{
T temp;
temp = x1; x1 = x2; x2 = temp;
}
void main()
{
char c1 = 'a', c2 = 'b';
int i1 = 10, i2 = 20;
swap(c1, c2);
swap(i1, i2);
}
C++ 中类模板的写法如下:
template <类型参数表>
class 类模板名{
成员函数和成员变量
};
类型参数表的写法如下:
class类塑参数1, class类型参数2, ...
类模板中的成员函数放到类模板定义外面写时的语法如下:
template <类型参数表>
返回值类型 类模板名<类型参数名列表>::成员函数名(参数表)
{
...
}
用类模板定义对象的写法如下:
类模板名<真实类型参数表> 对象名(构造函数实际参数表);
如果类模板有无参构造函数,那么也可以使用如下写法:
类模板名 <真实类型参数表> 对象名;
类模板看上去很像一个类。下面以 Pair 类模板为例来说明类模板的写法和用法。
#include <iostream>
#include <string>
using namespace std;
template <class T1,class T2>
class Pair
{
public:
Pair(T1 k,T2 v):key(k),value(v) { };
bool operator < (const Pair<T1,T2> & p) const;
T1 getKey(void) const;
T2 getValue(void) const;
private:
T1 key; //关键字
T2 value; //值
};
template<class T1,class T2> //每个函数前面都应该声明
bool Pair<T1,T2>::operator < (const Pair<T1,T2> & p) const //Pair的成员函数 operator <
{
return value < p.value; //"小"的意思就是值小
}
template<class T1,class T2> //每个函数前面都应该声明
T1 Pair<T1,T2>::getKey(void) const
{
return key;
}
template<class T1,class T2> //每个函数前面都应该声明
T2 Pair<T1,T2>::getValue(void) const
{
return value;
}
#include "template.h"
using namespace std;
int main()
{
Pair<string,int> Tom("Tom", 19); //实例化出一个类 Pair<string,int>
cout << Tom.getKey() << " " << Tom.getValue() << endl;
Pair<string,int> Ally("Ally", 20);
cout << Ally.getKey() << " " << Ally.getValue() << endl;
if(Tom < Ally)
{
cout << "Tom is younger than Ally" << endl;
}
else
{
cout << "Ally is younger than Tom" << endl;
}
return 0;
}