參數列表如函式簽章,標示參數數量、型別與唯一識別符。泛型參數皆視為 Object 或衍生型別,操作受限;模板支援型別、非型別 (常數運算式)、模板參數,並支援預設值。
template <class elemType, int size>
public ref class tStack {
array<elemType>^ m_stack = gcnew array<elemType>(size);
int top = 0;
};
template <class elemType, int size = 1024>
public ref class FixedSizeStack {};
FixedSizeStack<String^>^ s1 = gcnew FixedSizeStack<String^>(); // size=1024
FixedSizeStack<String^, 128>^ s2 = gcnew FixedSizeStack<String^, 128>(); // size=128
typedef void (*handler)(... array<Object^>^);
template <class elemType, int size = 1024, handler cback = &defaultHandler>
public ref class tStack {};
template <template <class T> class arena, class arenaType>
class Editor { arena<arenaType> m_arena; };
template <class elemType> public ref class tBuffer {};
Editor<tBuffer, String^>^ textEditor;
模板編譯期綁定,無效型別導致編譯錯誤。約束隱含於程式碼中 (如使用 operator==、T::NestedType),違反時編譯失敗。提供特製化版本繞過限制。
// 緊耦合 operator==
bool search(elemType et) { for each(e in m_buf) if (et == e) return true; }
// 靈活:成員函式模板接受比較器
template <class Comparer>
bool search(elemType et, Comparer comp) { for each(e in m_buf) if (comp(et, e)) return true; }
class EqualGuy { bool operator()(String^ s1, String^ s2) { return s1->CompareTo(s2) == 0; } };
sxc->search("Pooh", EqualGuy());
泛型執行期綁定,需編譯期過濾器確保型別有效。使用 where 子句:
generic <class elemType>
where elemType : IComparable
public ref class Container {
bool search(elemType et) { for each(e in m_buf) if (et->CompareTo(e)) return true; }
Container(int sz) { m_buf = gcnew array<elemType>(sz); }
};
預設約束為 Object (四個公共方法)。where elemType : IComparable 擴展操作集合為 Object ∩ IComparable。編譯器驗證實際型別參數符合約束:
Container<String^>^ sc; // 正確
Container<int>^ ic; // 正確
Container<StringBuilder^>^ sbc; // 錯誤:未實作 IComparable
where 條目,順序不拘。where T : IComparable, ICloneable, Image)。System::Array/Delegate/Enum/ValueType。where 僅一個類別約束。| 面向 | 模板 | 泛型 |
|---|---|---|
| 綁定時機 | 編譯期 | 執行期 |
| 約束形式 | 隱含 (使用點檢查) | 顯式 (where 子句) |
| 錯誤發現 | 編譯期 (使用時) | 編譯期 (定義點與構造點) |
| 設計自由度 | 高 (實作者導向) | 受限 (消費者導向) |
| 非型別參數 | 支援 | 不支援 |
| 特製化/部分特製化 | 支援 | 不支援 |
根據需求選擇:需執行期多型、跨組件二進位重用 → 泛型;需最大靈活度、非型別參數、特製化 → 模板。