模板是泛型编程的基础,泛型编程即以一种独立于任何特定类型的方式编写代码。
模板是创建泛型类或函数的蓝图或公式。库容器,比如迭代器和算法,都是泛型编程的例子,它们都使用了模板的概念。
函数模板
template <typename type>ret-type func-name(parameter list){// 函数的主体}
例子
#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;double f1 = 13.5;double f2 = 20.7;cout << "Max(f1, f2): " << Max(f1, f2) << endl;string s1 = "Hello";string s2 = "World";cout << "Max(s1, s2): " << Max(s1, s2) << endl;return 0;}
类模板
template <class type>class class-name {//}
例子
下面的实例定义了类 Stack<>,并实现了泛型方法来对元素进行入栈出栈操作
#include <iostream>#include <vector>#include <cstdlib>#include <string>#include <stdexcept>using namespace std;template <class T>class Stack {private:vector<T> elems; // 元素public:void push(T const&); // 入栈void pop(); // 出栈T top() const; // 返回栈顶元素bool empty() const{ // 如果为空则返回真。return elems.empty();}};template <class T>void Stack<T>::push (T const& elem){// 追加传入元素的副本elems.push_back(elem);}template <class T>void Stack<T>::pop (){if (elems.empty()) {throw out_of_range("Stack<>::pop(): empty stack");}// 删除最后一个元素elems.pop_back();}template <class T>T Stack<T>::top () const{if (elems.empty()) {throw out_of_range("Stack<>::top(): empty stack");}// 返回最后一个元素的副本return elems.back();}int main(){try {Stack<int> intStack; // int 类型的栈Stack<string> stringStack; // string 类型的栈// 操作 int 类型的栈intStack.push(7);cout << intStack.top() <<endl;// 操作 string 类型的栈stringStack.push("hello");cout << stringStack.top() << std::endl;stringStack.pop();stringStack.pop();}catch (exception const& ex) {cerr << "Exception: " << ex.what() <<endl;return -1;}}
