Template小结

来源:互联网 发布:mac字体大小 编辑:程序博客网 时间:2024/05/18 12:29

template<typename T>template<class T>

这两者基本是一样的,只是在C++早期版本,没有typename关键字,所以用class,但后来为了与类分开,所以有了typename,总的这两者可以替换使用,template <typename T>template<class T>作用相同。

用template实现swap

template<typename T>void swap(T &a, T& b) {    T t;    t = a;    a = b;    b = t;}

注意实际中要重新为swap起名,或者放在自己定义的名称空间中, 因为标准库函数中有swap, 回出现重定义的错误

类模板

(1)声明形式:
template
class 类模板名 {类成员声明};
在每一个成员函数的定义前加上template
返回值类型 模板名<模板形参名列表>::成员函数名{}

**important:

void funct(T a, T2 b) {  cout << a << endl;  cout << b << endl;}int main() {  int a = 1;  double b = 3.4;  string s = "sdaeg";  funct(a, b);  funct(b, s);  return 0;}

**模板形参名列表必须包含所有的模板名

(2)类模板是一个通用类模型,而不是具体类,不能用于创建对
象,只有经过实例化后才得到具体类,才能用于创建对象。
(3)一个类模板可以实例化为多个不同的具体类。
如定义了一个stack类,在main函数中可以有
stack s;
或者是stack s;

下面是用模板实现的栈代码:

#include<iostream>#include<algorithm>using namespace std;template<typename ElementType>class Stack{public:  Stack();  ~Stack();  void push(ElementType obj);  void pop();  ElementType getTop();  bool isEmpty() const;private:  struct Node {    ElementType element;    Node* next;  };  Node* top;};template<typename ElementType>Stack<ElementType>::Stack() {  top = NULL;}template<typename ElementType>Stack<ElementType>::~Stack() {  if (top != NULL) {    Node* t = top;    while (t != NULL) {      Node* p = t;      t = t->next;      delete p;    }  }  top = NULL;}template<typename ElementType>bool Stack<ElementType>::isEmpty() const {  return top == NULL;}template<typename ElementType>ElementType Stack<ElementType>::getTop() {  return top->element;}template<typename ElementType>void Stack<ElementType>::push(ElementType obj) {  Node* temp;    temp = new Node;    temp->element = (obj, top);    top = temp;}template<typename ElementType>void Stack<ElementType>::pop() {  Node* temp;  if (top != NULL) {    temp = top;    top = top->next;    delete temp;  }}int main() {  Stack<int> stack;  for (int i = 1; i < 9; i++)  stack.push(i);  while (!stack.isEmpty()) {    cout << stack.getTop() << " ";    stack.pop();  }  cout << endl;  return 0;}//  输出结果体现后进先出的特点
0 0