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

C++ 類別模板完整指南:泛型程式設計核心技術

     編輯:C++ 入門

模板基礎

模板實現泛型程式設計:以型別為參數編寫通用程式碼,編譯器根據實際型別具現化生成特定版本。

語法

template <class T>        // 或 typename T
class ClassName {
    // 使用 T 作為型別參數
};

Array 類別模板完整實作

#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;
}

模板進階特性

1. 多型別參數

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; }
};

2. 非型別參數(編譯期常數)

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;

3. 預設模板參數

template <class T = int, int Size = 10>
class Buffer { /* ... */ };

Buffer<> buf;  // 等同 Buffer<int, 10>

4. 模板特化

// 通用版本
template <class T>
class Container { /* ... */ };

// 全特化:針對 char* 優化
template <>
class Container<char*> { /* 專門處理 C 字串 */ };

// 偏特化:針對指標類型
template <class T>
class Container<T*> { /* 通用指標處理 */ };

模板實作細節與陷阱

1. 定義與宣告分離問題

模板成員函式定義通常必須放在頭文件中,否則連結器找不到具現化代碼。

2. 關鍵字 typename 與 class

  • 模板參數列表中等價
  • 依賴型別名稱前必須用 typename:typename T::iterator

3. 靜態成員與模板

template <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;

標準庫模板應用

模板元程式設計 (TMP) 簡介

利用模板在編譯期執行計算:

// 編譯期計算階乘
template <int N>
struct Factorial {
    static const int value = N * Factorial<N-1>::value;
};

template <>
struct Factorial<0> {
    static const int value = 1;
};

// 使用:Factorial<5>::value → 120 (編譯期常數)

現代 C++ 模板最佳實務

  1. 使用 auto 配合模板推導簡化代碼
  2. 善用 std::enable_if / Concepts (C++20) 進行約束
  3. 優先考慮 std::function、lambda 替代仿函式模板
  4. 避免過度模板化導致編譯緩慢、代碼膨脹
  5. 使用 extern template 顯式具現化減少編譯開銷

總結

類別模板是 C++ 泛型程式設計的基石。掌握型別/非型別參數、特化機制、靜態成員獨立性、定義可見性要求,並熟悉 STL 容器模板應用,能編寫出高復用、型別安全、零開銷抽象的現代 C++ 代碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
容器適用場景
vector<T>動態陣列,隨機存取快
list<T>雙向鏈表,插入刪除快
deque<T>雙端佇列,首尾操作快
map<K,V>鍵值對,有序,紅黑樹
unordered_map<K,V>雜湊表,平均 O(1)
set<T>唯一元素集合,有序