首先看看类模板
#include <iostream> // using cout and endl
#include <fstream> // using operate file
#include <cmath> // using sqrt
#include <ctime> // using time
#include <cstdlib> // using rand
#include <iomanip> // using setw
#include <vector> // using vector
#include <cstring> // using strlen
#include <exception> // using standard exception
#include <stdexcept> // using out_of_range func
using namespace std;
template <class T>
class my_class{
public:
vector<T> element;
void push(T const& ele){
element.push_back(ele); // 入栈
}
void pop();
T top() const;
bool empty() const{
return element.empty(); // 栈为空
}
};
template <typename T>
void my_class<T>::pop(){
if(element.empty()){
throw out_of_range("out of range"); // 判断栈元素越界
}
element.pop_back(); // 出栈
}
template <typename T>
T my_class<T>::top()const{
if(element.empty()){
throw out_of_range("out of range"); // 抛出异常
}
return element.back(); // 栈顶元素
}
int main(){
try{
my_class<int> int_class;
int_class.push(7);
cout << int_class.top() << endl;
int_class.pop();
cout << int_class.top() << endl;
}catch(exception const & e){
cout << e.what() << endl;
}
return 0;
}
函数模板
#include <iostream>
using namespace std;
template <typename T>
inline T const & Max(T const & a, T const & b){
return a>b?a:b;
}
int main(){
int a1=9, b1 = 10;
double a2=18, b2=90;
cout << Max(a1, b1) << endl;
cout << Max(a2, b2) << endl;
return 0;
}
template <typename T> 可以修改成 template <class T>
模板实际上就是脱离类型。