示例 加法
类外实现函数时,必须使用显示指定模板
#include<iostream>
using namespace std;
template<class T>
class A {
private:
T first;
T second;
public:
A(T a, T b): first(a), second(b) {};
void add();
};
template<class T>
void A<T>::add() {
cout << first + second<<endl;
}
void testA() {
A<int> a(1, 2);
a.add();
A<double> b(2.5,3);
b.add();
}
int main() {
testA();
}
示例2 封装Stack
#include<iostream>
#include<vector>
using namespace std;
template<class T>
class Stack {
private:
vector<T> elems;
public:
void push(T const&);
void pop();
T top() const;
bool empty() const { return elems.empty(); }
};
template<class T>
void Stack<T>::push(T const& elem) {
elems.push_back(elem);
}
template<class T>
void Stack<T>::pop() {
if (elems.empty()) {
throw out_of_range("Stack<>::pop(): empty stack");
}
elems.pop_back();
}
template<class T>
T Stack<T>::top() const {
if (elems.empty()) {
throw out_of_range("Stack<>::top(): empty stack");
}
return elems.back();
}
void testStack() {
Stack<int> intStack;
intStack.push(10);
intStack.push(20);
intStack.push(30);
cout << intStack.top() << endl;
intStack.pop();
cout << intStack.top() << endl;
intStack.pop();
cout << intStack.top() << endl;
intStack.pop();
}
int main() {
testStack();
try {
Stack<string> strStack;
strStack.push("Hello,world");
strStack.push("Hello,C++");
cout << strStack.top() << endl;
strStack.pop();
cout << strStack.top() << endl;
strStack.pop();
strStack.pop();
}
catch (exception const& ex) {
cout << ex.what() << endl;
return 1;
}
return 0;
}