函數模板特化(非多載)針對特定模板參數提供專屬實作。使用 template<> 空尖括號表示支援原版本所有模板參數。注意:存在非模板函數時,匹配度相同優先使用非模板版本。
/*
* CppPrimer.cpp - 函數模板特化範例
* Created on: 2013.12.9
* Author: Caroline
* eclipse cdt, gcc 4.8.1
*/
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
// 通用版本:適用於支援 < 運算子的型別
template <typename T>
bool compare(const T& t1, const T& t2) {
std::cout << "first version" << std::endl;
return (t1 < t2) ? true : false;
}
// 函數模板特化:const char* 指標比較內容而非地址
template<>
bool compare(const char* const &p1, const char* const &p2) {
std::cout << "third version" << std::endl;
return strcmp(p1, p2);
}
// 非模板版本(註解掉):同樣處理 const char*,優先級高於特化
/*
bool compare(const char* const &p1, const char* const &p2) {
std::cout << "forth version" << std::endl;
return strcmp(p1, p2);
}
*/
// 重載版本:字串字面值(陣列引用)非型別參數
template<unsigned N, unsigned M>
bool compare(const char (&p1)[N], const char (&p2)[M]) {
std::cout << "second version" << std::endl;
return strcmp(p1, p2);
}
int main(void) {
const char* w("Wendy");
const char* c("Caroline");
// 呼叫特化版本:比較指標指向的字串內容
if (compare(c, w)) {
std::cout << "Caroline is long." << std::endl;
} else {
std::cout << "Wendy is long." << std::endl;
}
// 呼叫重載版本:推導陣列大小 N=9, M=6
if (compare("Caroline", "Wendy")) {
std::cout << "Caroline is long." << std::endl;
} else {
std::cout << "Wendy is long." << std::endl;
}
return 0;
}
third version Caroline is long. second version Caroline is long.
| 特性 | 模板特化 | 函數重載 |
|---|---|---|
| 語法 | template<> | 同名不同參數 |
| 本質 | 實例化特定模板 | 獨立函數 |
| 參數推導 | 不參與推導 | 參與推導 |
| 優先級 | 低於非模板 | 同非模板 |