声明和定义都放在.hpp中
演示代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| #pragma once
namespace lt { template<class T> class Stack { private: T* arr; int top; int size; void resize(int size); public: Stack(); Stack(int size); ~Stack(); void Push(T e); void Pop(); T Top(); bool Empty(); }; }
#include<cstdlib> #include"datastructure/Stack.hpp" using namespace lt; #define MALLOCSIZE 256 template<class T> Stack<T>::Stack() :size(MALLOCSIZE), top(0), arr(NULL) { arr = (T*)malloc(sizeof(T) * size); } template<class T> Stack<T>::Stack(int _size) : size(_size), top(0), arr(NULL) { arr = (T*)malloc(sizeof(T) * size); } template<class T> Stack<T>::~Stack() { free(arr); } template<class T> void Stack<T>::Push(T e) { if (size <= top) { resize(size + MALLOCSIZE); } arr[top++] = e; } template<class T> void Stack<T>::Pop() { top--; } template<class T> T Stack<T>::Top() { return arr[top - 1]; } template<class T> bool Stack<T>::Empty() { return top == 0; } template<class T> void Stack<T>::resize(int _size) { arr = (T*)realloc(arr, sizeof(T) * _size); size = _size; }
|
声明放在.hpp文件中,定义放在.cpp文件中
声明放在.hpp文件中,定义放在.cpp文件中,需要在.cpp文件中将所有用到的类型显示实例化
编译器怎么处理模板呢?本质上来说,模板可被编译器产生多种多样函数和类的代码。只有当被使用的时候,编译器才会产生用于这种类型的代码。模板不是直接编译成以后需要的各种类的实现,而是将模板代码解析放入内存中,当编译某个编译单元需要用到该模板,则会按需产生相应的代码。实例化是编译器确定特定模板与特定参数集一起使用并在模板上执行参数替换以生成要编译的类或函数以及最终编译为模板的二进制代码的过程。
.hpp演示代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| #pragma once
namespace lt { template<class T> class Stack { private: T* arr; int top; int size; void resize(int size); public: Stack(); Stack(int size); ~Stack(); void Push(T e); void Pop(); T Top(); bool Empty(); }; }
|
.cpp演示代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| #include<cstdlib> #include"datastructure/Stack.hpp" using namespace lt; #define MALLOCSIZE 64 template<class T> lt::Stack<T>::Stack():size(MALLOCSIZE),top(0),arr(NULL) { arr = (T*)malloc(sizeof(T) * size); } template<class T> lt::Stack<T>::Stack(int _size):size(_size), top(0), arr(NULL) { arr = (T*)malloc(sizeof(T) * size); } template<class T> lt::Stack<T>::~Stack() { free(arr); } template<class T> void lt::Stack<T>::Push(T e) { if (size <= top) { resize(size+ MALLOCSIZE); } arr[top++] = e; } template<class T> void lt::Stack<T>::Pop() { top--; } template<class T> T lt::Stack<T>::Top() { return arr[top-1]; } template<class T> bool lt::Stack<T>::Empty() { return top == 0; } template<class T> void lt::Stack<T>::resize(int _size) { arr = (T*)realloc(arr,sizeof(T) * _size); size = _size; }
template class Stack<int>;
|