函数模板
//函数模板
template<class T>//模板参数列表 --参数类型
void Swap(T& x1, T& x2)//函数参数列表 -- 参数对象
{
T x = x1;
x1 = x2;
x2 = x;
}
int main()
{
int a = 10, b = 3;
Swap(a, b);
return 0;
}
template<class T>
T Add(const T& left, const T& right)
{
return left + right;
}
int main()
{
int a1 = 10, a2 = 11;
double d1 = 3.2, d2 = 3.1;
cout << Add((double)a1, d2) << endl;
//显示实例化
cout << Add<int>(a1, d2) << endl;
cout << Add<double>(a1, d2) << endl;
return 0;
}
如果想直接用Add(a1,d2)
可以像下面这样
template<class T1,class T2>
T1 Add(const T1& left, const T2& right)//返回值取决定因素
{
return left + right;
}
上面两种方法都可以同时出现
//专门处理int的加法函数(现成)
int Add(int left, int right)
{
return left + right;
}
//所有类型通用的加法函数(模板)
template<class T1, class T2>
T1 Add(const T1& left, const T2& right)//返回值取决定因素
{
return left + right;
}
int main()
{
int a1 = 10, a2 = 11;
double d1 = 3.2, d2 = 3.1;
cout << Add(a1, a2) << endl;//调用现成的
cout << Add(d1, d2) << endl;//调用模板
cout << Add(a1, d2) << endl;//调用模板
}
类模板
// 类模板
//Stack类名
//Stack<T>类型
template<class T>
class Stack
{
public:
Stack(int capacity = 4)//全缺省
:_top(0)
, _capacity(capacity)
{
_a = new T[capacity];
}
~Stack()
{
delete[] _a;
_a = nullptr;
_top = _capacity = 0;
}
void Push(const T& x);
private:
T* _a;
int _top;
int _capacity;
};
template<class T>
void Stack<T>::Push(const T& x)//要指定类域,才完整
{
}
int main()
{
Stack<int> st1; //存储int
Stack<double> st2;//存储double
Stack<char> st3; //存储char
return 0;
}