類模板是 C++ 泛型編程核心機制。掌握語法細節、成員定義規則、當前類型注入,避開常見編譯錯誤。
template <typename T> // 或 class T
class Container {
T value_;
public:
Container(T v) : value_(std::move(v)) {}
T get() const { return value_; }
void set(T v) { value_ = std::move(v); }
};
// 使用:必須顯式指定模板參數
Container<int> c1(42);
Container<std::string> c2("hello");
// 必須重複模板參數列表
template <typename T>
T Container<T>::get() const { return value_; }
template <typename T>
void Container<T>::set(T v) { value_ = std::move(v); }
在類模板**內部**,裸名 `Container` 等價於 `Container
template <typename T>
class Node {
Node* next_; // 等價 Node*,無需寫模板參數
Node& self() { return *this; } // 返回 Node&
// 但靜態成員、嵌套類、模板別名需完整寫法
static Node* create(); // 必須寫 Node
using value_type = T; // 類型別名
};
這叫 **Injected Class Name**,簡化內部引用。
template <typename T>
class Wrapper {
T data_;
public:
// C++11 初始化列表構造
Wrapper(std::initializer_list<T> il) : data_(il.size() ? *il.begin() : T{}) {}
// 完美轉發構造
template <typename... Args>
Wrapper(Args&&... args) : data_(std::forward<Args>(args)...) {}
};
template <typename T>
class Iterator {
public:
// 前置 ++it:返回引用,無參數
Iterator& operator++() { /* 前進 */ return *this; }
// 後置 it++:int 偽參數區分,返回舊值副本
Iterator operator++(int) { Iterator tmp = *this; ++*this; return tmp; }
};
| 錯誤 | 原因 | 修復 |
|---|---|---|
| undefined reference to `Container<int>::get()` | 成員定義在 .cpp,模板實例化不可見 | 移至頭文件或 .tpp 並 `#include` |
| 'Container' does not name a type | 類外定義漏寫 `Container | 加上模板參數 |
| no match for 'operator++' | 後置++漏寫 int 參數 | 加上 `operator++(int)` |
類模板將「演算法/結構」與「具體類型」分離,是 C++ 泛型抽象的基石。精通其語法細節,是進階 C++ 開發者的必修課。