用另一种方式重用代码
函数模板:function template:
template
void swap(T& x,T& y){
T temp = x;
x = y;
y = temp;
}
T 可以是 参数类型或者 自定义类型
.h文件为:
#ifndef TEMPALTE_H
#define TEMPALTE_H
class tempalte
{
public:
tempalte();
virtual ~tempalte();
template<class T> //template 是关键字,函数声明
void swap(T& x,T& y);
};
#endif // TEMPALTE_H'''
.cpp文件为:
#include "tempalte.h"
tempalte::tempalte()
{
//ctor
}
tempalte::~tempalte()
{
//dtor
}
template<class T> //函数定义
void swap(T& x,T& y){
T temp = x;
x = y;
y = temp;
}
main.cpp文件为:
#include <iostream>
#include <tempalte.h>
using namespace std;
int main()
{ int a=1,b=2;
swap(a,b); //函数调用
cout<<"a b :"<<a<<' '<<b<<endl;
char c='c',d='d';
swap(c,d); //函数调用
cout << "c d :" << c<<' '<<d<<endl;
return 0;
}
//输出: a b :2 1
// c d :d c