模板(Template)指C++程序设计语言中采用类型作为参数的程序设计
1、函数模板
template<typename T> void swap1(T& a, T& b);
int main() {
int num1 = 10;
int num2 = 20;
int& a = num1;
int& b = num2;
swap1<int>(a, b);
printf("num1=%d num2=%d\n",num1,num2);
float f1 = 1.234f;
float f2 = 2.345f;
float& c = f1;
float& d = f2;
swap1<float>(c, d);
printf("f1=%.3f f2=%.3f\n",f1,f2);
}
template<typename T> void swap1(T& a, T& b) {
T temp;
temp = a;
a = b;
b = temp;
}
2、类模板
//
template<class T>class Stack {
public:
Stack();
~Stack();
void push(T t);
T pop();
bool isEmpty();
private:
T* m_pT;
int m_max_size;
int m_size;
};
//Stack.hpp
template<class T>class Stack {
public:
Stack();
~Stack();
void push(T t);
T pop();
bool isEmpty();
private:
T* m_pT;
int m_max_size;
int m_size;
};
//
int main() {
Stack<int> intStack;
intStack.push(1);
intStack.push(2);
intStack.push(3);
while (!intStack.isEmpty()) {
printf("num:%d\n",intStack.pop());
}
}
//Stack.cpp
#include "Stack.hpp"
template<class T> Stack<T>::Stack() {
m_max_size = 100;
m_size = 0;
m_pT = new T[m_max_size];
}
template<class T> Stack<T>::~Stack() {
delete [] m_pT;
}
//入栈
template<class T> void Stack<T>::push(T t) {
m_pT[m_size++] = t;
}
//出栈
template<class T> T Stack<T>::pop() {
T t = m_pT[--m_size];
return t;
}
//判断栈空
template<class T> bool Stack<T>::isEmpty() {
return m_size == 0;
}