首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++/CLI 泛型與 C++ 模板深度對比:參數列表、約束與設計哲學

     編輯:關於C++

參數列表機制

參數列表如函式簽章,標示參數數量、型別與唯一識別符。泛型參數皆視為 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;

型別參數約束:隱含 vs 顯式

模板:隱含約束 (SFINAE)

模板編譯期綁定,無效型別導致編譯錯誤。約束隱含於程式碼中 (如使用 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 子句)
錯誤發現編譯期 (使用時)編譯期 (定義點與構造點)
設計自由度高 (實作者導向)受限 (消費者導向)
非型別參數支援不支援
特製化/部分特製化支援不支援

根據需求選擇:需執行期多型、跨組件二進位重用 → 泛型;需最大靈活度、非型別參數、特製化 → 模板。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved