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