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

重學 C++ (十二) —— 模板特化與偏特化完整指南

     編輯:關於C++

模板特化允許為特定類型提供定制實現;偏特化則在多參數模板中僅特化部分參數。本文系統梳理類/函數模板的完全特化、偏特化語法與匹配優先級規則。

一、模板基礎回顧

1.1 類模板

template <class T>
class Compare {
public:
    bool isEqual(T a, T b) { return a == b; }
};

1.2 函數模板

template <class T>
bool isEqual(T a, T b) { return a == b; }

二、完全特化

2.1 類模板完全特化

template <>
class Compare<char*> { // 針對 char* 特化
public:
    bool isEqual(char* a, char* b) { return strcmp(a, b) == 0; }
};

注意:類外定義成員時不加 template <>。

2.2 類模板成員特化(僅特化某個成員函數)

template <>
void vector<const char*>::push_back(const char* const& val) { ... }

2.3 函數模板完全特化

template <>
bool isEqual<char*>(char* a, char* b) { return strcmp(a, b) == 0; }

三、偏特化

3.1 類模板偏特化(多參數時僅綁定部分)

// 原始模板
template <class T, class Alloc> class vector { ... };

// 偏特化:T 綁定為 bool,Alloc 保留
template <class Alloc>
class vector<bool, Alloc> { ... };

3.2 函數模板不支援偏特化

但可通過函數重載達到同樣效果:

template <class T> void f(T);        // (a) 基模板
template <class T> void f(T*);       // (b) 重載,針對指針類型
// (b) 不是偏特化,而是獨立模板,參與重載解析

四、特化匹配優先級規則

4.1 類模板:最特化者優先

template <class T> class Vector { ... };           // (a) 通用
template <class T> class Vector<T*> { ... };      // (b) 指針特化
template <> class Vector<void*> { ... };          // (c) void* 完全特化

Vector      v1; // (a)
Vector     v2; // (b) 比 (a) 更特化
Vector    v3; // (c) 最特化

4.2 函數模板:非模板 > 完全特化 > 重載(更特化) > 基模板

template <class T> void f(T);           // (d)
template <class T> void f(int, T, double); // (e)
template <class T> void f(T*);          // (f)
template <> void f<int>(int);           // (g) 完全特化
void f(double);                         // (h) 非模板

f(true);    // (d) T=bool
f(1,2,3.0); // (e) T=int
f(&i);      // (f) T=int*
f(1);       // (g) 完全特化優先於 (d)
f(3.14);    // (h) 非模板最高優先級

五、工程避坑指南

  1. 類模板特化必須在命名空間作用域,不能在類內部。
  2. 函數模板不要寫偏特化,改用重載或啟用 enable_if / 概念 约束。
  3. 完全特化聲明加 template <>,定義處不加。
  4. 偏特化時,未特化參數須保持模板參數列表順序。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved