模板是泛型编程的基础,泛型编程即以一种独立于任何特定类型的方式编写代码。
模板是创建泛型类或函数公式。STL中的容器、迭代器、算法,都是泛型编程的例子,它们都使用了模板的概念。比如 向量,我们可以定义许多不同类型的向量,比如 vector< int > 或 vector < string >。
函数模板
#include <iostream>
#include <string>
using namespace std;
template <typename T>
inline T const& Max (T const& a, T const& b)
{
return a < b ? b:a;
}
int main ()
{
int i = 39;
int j = 20;
cout << "Max(i, j): " << Max(i, j) << endl;
string s1 = "Hello";
string s2 = "World";
cout << "Max(s1, s2): " << Max(s1, s2) << endl;
return 0;
}
类模板
#include <iostream>
#include <string>
#include <vector>
using namespace std;
template <class T>
class stack{
private:
vector<T> v;
public:
void push(T const& a){
v.push_back(a);
}
void pop(){
v.pop_back();
}
T top() const{
return v.back();
}
bool empty(){
return v.empty();
}
};
int main()
{
stack<int> stk;
stk.push(1);
stk.push(3);
stk.push(5);
stk.pop();
cout << stk.top() <<endl;
cout << stk.empty() <<endl;
}