template// 或 class T1, class T2 class ClassName { // 成員可使用 T1, T2 };
template 與 class 之間不能有分號templateclass Point { T1 x; T2 y; public: Point(T1 x, T2 y) : x(x), y(y) {} T1 getX() const; void setX(T1 v); T2 getY() const; void setY(T2 v); };
templateT1 Point ::getX() const { return x; } template void Point ::setX(T1 v) { x = v; } // T2 版本同理...
關鍵:
1. 必須帶上 template 標頭
2. 類名後附 <T1, T2> (不寫 typename)
3. 參數順序與宣告一致
p1(10, 20); Pointp2(10, "東京180度"); Point p3("東京", "北緯"); // 物件指標 (雙邊必須一致) Point * p4 = new Point (1.5, 2.5); // 錯誤:Point * p = new Point (...); // 錯誤:Point * p = new Point(...);
與函數模板不同,類模板不支援型別推導 (C++17 前),必須顯式提供模板實參。
#includeusing namespace std; template class Point { T1 x; T2 y; public: Point(T1 x, T2 y) : x(x), y(y) {} T1 getX() const; T2 getY() const; void setX(T1 v); void setY(T2 v); }; template T1 Point ::getX() const { return x; } template T2 Point ::getY() const { return y; } template void Point ::setX(T1 v) { x = v; } template void Point ::setY(T2 v) { y = v; } int main() { Point p1(10, 20); cout << "x=" << p1.getX() << ", y=" << p1.getY() << endl; Point p2(10, "東京180度"); cout << "x=" << p2.getX() << ", y=" << p2.getY() << endl; Point * p3 = new Point ("東京", "北緯"); cout << "x=" << p3->getX() << ", y=" << p3->getY() << endl; delete p3; return 0; }
vector<T>, list<T>, map<K,V>unique_ptr<T>, shared_ptr<T>is_integral<T>, remove_reference<T>類模板將「型別」提升為參數,實現代碼復用與型別安全的完美平衡。掌握「宣告語法、類外定義雙重模板標頭、顯式實例化、指標雙邊一致」四大核心語法,即可自如構建泛型類別,邁向庫級開發。