c++ 模板
测试代码。my_template.h头文件内容如下:
#ifndef MY_TEMPLATE_HEADER_H
#define MY_TEMPLATE_HEADER_H// 函数模板示例 函数模板的 T 作用域仅限于此函数
template<typename T>
T my_max(T a, T b) {return (a > b) ? a : b;
}// 类模板示例 类模板的 T 作用域仅限于此类定义
template<class T>
class MyStack {
private:T* elements;int top;int capacity;
public:MyStack(int size = 10) : capacity(size), top(-1) {elements = new T[capacity];}~MyStack() {delete[] elements;}void push(const T& item) {if (top >= capacity - 1) {throw std::overflow_error("Stack is full");}elements[++top] = item;}T pop() {if (top < 0) {throw std::underflow_error("Stack is empty");}return elements[top--];}bool empty() const {return top == -1;}
};#endif
测试代码:
#include "my_template.h"void testTemplate() {int maxVal = my_max(3, 5);std::cout << "maxVal: " << maxVal << endl;MyStack<int> stack;stack.push(1);stack.push(2);stack.push(3);std::cout << "top: " << stack.pop() << endl;
}
打印:
ok! 注意:类模板和函数模板通常写在头文件中。