一、函数模板
1. 模板
template<函数参数模板>
类型名 函数名(参数表)
{
函数体的定义
}
2. 例子
#include<iostream>
using namespace std;
template <typename T>// 或者 template <class T>
T abs(T x)
{
return x < 0 ? -x : x;
}
int main()
{
int n = 5;
double m = -5.5;
cout << abs(n) << endl;
cout << abs(m) << endl;
return 0;
}
二、类模板
1. 模板
类模板声明:
template<模板参数表>
class 类名
{
类成员声明
}
类模板以外定义成员函数:
template<模板参数表>
类型名 类名<模板参数识别符列表>::函数名(参数表)
使用模板类建立对象时:
模板名<函数参数表>对象名1, …对象名n;
2. 例子
#include<iostream>
using namespace std;
struct Student {
int id;
float gpa;
};
template <class T>
class Store {
private:
T item;
bool haveValue;
public:
Store();
T& getElem();
void putElem(const T& x);
};
template<class T>
Store<T>::Store() :haveValue(false) {}
template <class T>
T& Store<T>::getElem()
{
if (!haveValue) {
cout << "no item present!" << endl;
exit(1);
}
return item;
}
template<class T>
void Store<T>::putElem(const T& x)
{
haveValue = true;
item = x;
}
int main()
{
Store<int>s1, s2;
s1.putElem(3);
s2.putElem(-7);
cout << s1.getElem() << " " << s2.getElem() << endl;
return 0;
}