templateclass ClassName { // 成員宣告 T data; public: void func(T arg); }; // 成員函數定義需加模板前綴 template void ClassName ::func(T arg) { ... }
ClassNameobj; // 產生具體類別 ClassName ClassName obj2; // 另一個具體類別
模板參數不限於型別,整數、指標、參考等編譯期常量皆可。
templateclass Stack2 { T elems_[MAX_SIZE]; int top_; public: Stack2() : top_(-1) {} void Push(const T& e) { if (top_ + 1 >= MAX_SIZE) throw out_of_range("Stack full"); elems_[++top_] = e; } void Pop() { if (top_ < 0) throw out_of_range("Stack empty"); --top_; } T& Top() { if (top_ < 0) throw out_of_range("Stack empty"); return elems_[top_]; } bool Empty() const { return top_ == -1; } };
int main() {
Stack2 s; // 型別 int,容量 5
s.Push(1); s.Push(2); s.Push(3);
while (!s.Empty()) { cout << s.Top() << endl; s.Pop(); }
return 0;
}
template void Stack2::Push(...) 。