定义模板函数:
templateTest.h
#include "stdafx.h"
using namespace std;
template<typename T>
T const AddTem(T const a,T const b)
{
return a + b;
}
template<typename T2>
void swaps(T2& a,T2& b)
{
T2 temp;
temp = a;
a = b;
b = temp;
}
template<typename T3>
void print(const T3 &a, T3 const &b)
{
cout<<endl<<"使用模板后, a="<<a<<" b="<<b<<endl;
}若把template<typename T> 与后边的两个template写在一块儿,编译时会出错
使用时直接调用:
int an = 3, bn = 4;
double ad = 5.3, bd = 2.3;
char ac = 'a', bc = 'b';
swap12(an, bn);
print(an, bn);
若函数模板重载,在templateTest.h中加上:
template<typename T4>
T4 const AddIem(T4 const a, T4 const b, T4 const c)
{
return a + b + c;
}同理,类模板的定义:
template<typename T5>
struct Node
{
Node(T5 &d):c(d),next(0),pref(0){}
T5 c;
Node *next, *pref;
};
template<typename T6>
class List
{
Node<T6> *first, *last;
public:
List(){first = nullptr,last = nullptr};
void add(){}
~List(){};
};写的时候,类定义最后的’;‘号忘了,编译时报错位置定位在cpp文件上,说第一个函数void前缺少’;‘templateTest.h刚好在此函数前边,应该是编译顺序的问题吧。

被折叠的 条评论
为什么被折叠?



