模板實現泛型程式設計:以型別為參數編寫通用程式碼,編譯器根據實際型別具現化生成特定版本。
template <class T> // 或 typename T
class ClassName {
// 使用 T 作為型別參數
};
#include <iostream>
using namespace std;
template <class T>
class Array {
int size;
T *data; // 動態陣列指標
public:
// 建構函式
Array(int sz = 1) : size(sz) {
data = new T[size];
}
// 解構函式
~Array() {
delete[] data;
}
// 輸入資料
void fillArray() {
cout << "請輸入 " << size << " 個資料:" << endl;
for (int i = 0; i < size; ++i) {
cout << "第 " << i+1 << " 個:";
cin >> data[i];
}
}
// 顯示資料
void dispArray() const {
for (int i = 0; i < size; ++i)
cout << data[i] << " ";
cout << endl;
}
// 存取元素(邊界檢查版本)
T& at(int index) {
if (index < 0 || index >= size) throw out_of_range("Index out of range");
return data[index];
}
int getSize() const { return size; }
};
// 類別模板成員函式定義在類別外部時,需保留 template 前綴
template <class T>
void Array<T>::fillArray() { /* 同前 */ }
template <class T>
void Array<T>::dispArray() const { /* 同前 */ }
int main() {
// 具現化不同型別版本
Array<int> ai(5);
Array<double> ad(3);
Array<char> ac(10);
cout << "=== 整數陣列 ===" << endl;
ai.fillArray();
ai.dispArray();
cout << "=== 雙精度陣列 ===" << endl;
ad.fillArray();
ad.dispArray();
cout << "=== 字元陣列 ===" << endl;
ac.fillArray();
ac.dispArray();
return 0;
}
template <class K, class V>
class Pair {
K key; V value;
public:
Pair(K k, V v) : key(k), value(v) {}
K getKey() const { return key; }
V getValue() const { return value; }
};
template <class T, int N>
class FixedArray {
T data[N];
public:
T& operator[](int i) { return data[i]; }
int size() const { return N; }
};
// 使用:FixedArray<int, 100> arr;
template <class T = int, int Size = 10>
class Buffer { /* ... */ };
Buffer<> buf; // 等同 Buffer<int, 10>
// 通用版本
template <class T>
class Container { /* ... */ };
// 全特化:針對 char* 優化
template <>
class Container<char*> { /* 專門處理 C 字串 */ };
// 偏特化:針對指標類型
template <class T>
class Container<T*> { /* 通用指標處理 */ };
模板成員函式定義通常必須放在頭文件中,否則連結器找不到具現化代碼。
typename 與 classtypename:typename T::iteratortemplate <class T>
class Counter {
static int count; // 每個具現化類別擁有獨立的 static 成員
public:
Counter() { ++count; }
static int getCount() { return count; }
};
// 每個 T 都需要單獨定義
template <class T> int Counter<T>::count = 0;
| 容器 | 適用場景 |
|---|---|
vector<T> | 動態陣列,隨機存取快 |
list<T> | 雙向鏈表,插入刪除快 |
deque<T> | 雙端佇列,首尾操作快 |
map<K,V> | 鍵值對,有序,紅黑樹 |
unordered_map<K,V> | 雜湊表,平均 O(1) |
set<T> | 唯一元素集合,有序 |