C++ Template应用详解

2020-01-06 16:35:07于海丽


//shape.h
class Shape {

};
class Circle : public Shape {
};

然后我们希望可以这么使用:


//main.cpp
#include <stdio.h>
#include "stack.h"
#include "shape.h"
int main() {
  Stack<Circle*> pcircleStack;
  Stack<Shape*> pshapeStack;
  pcircleStack.push(new Circle);
  pshapeStack = pcircleStack;
  return 0;
}

这里是无法编译的,因为Stack<Shape*>不是Stack<Circle*>的父类,然而我们却希望代码可以这么工作,那我们就要定义转换运算符了,Stack


//statck.h
template <class T> class Stack {
  public:
    Stack();
    ~Stack();
    void push(T t);
    T pop();
    bool isEmpty();
    template<class T2> operator Stack<T2>();
  private:
    T *m_pT;    
    int m_maxSize;
    int m_size;
};

#include "stack.cpp"

template <class T> Stack<T>::Stack(){
  m_maxSize = 100;   
  m_size = 0;
  m_pT = new T[m_maxSize];
}
template <class T> Stack<T>::~Stack() {
  delete [] m_pT ;
}
    
template <class T> void Stack<T>::push(T t) {
  m_size++;
  m_pT[m_size - 1] = t;
  
}
template <class T> T Stack<T>::pop() {
  T t = m_pT[m_size - 1];
  m_size--;
  return t;
}
template <class T> bool Stack<T>::isEmpty() {
  return m_size == 0;
}

template <class T> template <class T2> Stack<T>::operator Stack<T2>() {
  Stack<T2> StackT2;
  for (int i = 0; i < m_size; i++) {
    StackT2.push((T2)m_pT[m_size - 1]);
  }
  return StackT2;
}

//main.cpp
#include <stdio.h>
#include "stack.h"
#include "shape.h"
int main() {
  Stack<Circle*> pcircleStack;
  Stack<Shape*> pshapeStack;
  pcircleStack.push(new Circle);
  pshapeStack = pcircleStack;
  return 0;
}

这样,Stack<Circle>或者Stack<Circle*>就可以自动转换为Stack<Shape>或者Stack<Shape*>,如果转换的类型是Stack<int>到Stack<Shape>,编译器会报错。

其他

一个类没有模板参数,但是成员函数有模板参数,是可行的,


class Util {
  public:
    template <class T> bool equal(T t1, T t2) {
      return t1 == t2;
    }
};

int main() {
  Util util;
  int a = 1, b = 2;
  util.equal<int>(1, 2);
  return 0;
}

甚至可以把Util的equal声明为static,


class Util {
  public:
     template <class T> static bool equal(T t1, T t2) {
      return t1 == t2;
    }
};

int main() {
  int a = 1, b = 2;
  Util::equal<int>(1, 2);
  return 0;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持ASPKU。


注:相关教程知识阅读请移步到C++教程频道。