C++ 模板是泛型程式設計的基石。與物件導向在執行期決定型別不同,泛型程式設計在編譯期即確定型別,實現零開銷抽象。
typename 或 class,推薦使用 typename 語意更明確/*
* cppprimer.cpp - 函數模板範例
* Created on: 2013.11.21
* Author: Caroline
* eclipse cdt, gcc 4.8.1
*/
#include <iostream>
#include <vector>
#include <functional> // less<>
#include <cstring> // strcmp
// 通用版本:使用 std::less 避免指標地址比較問題
template <typename T>
int compare(const T &v1, const T &v2) {
if (std::less<T>()(v1, v2)) return -1;
if (std::less<T>()(v2, v1)) return 1;
return 0;
}
// 字串字面值專用版本:非型別模板參數 N, M 推導陣列大小
template<unsigned N, unsigned M>
int compare(const char (&p1)[N], const char (&p2)[M]) {
std::cout << "N = " << N << " M = " << M << std::endl;
return std::strcmp(p1, p2); // 正確比較字串內容
}
int main(void) {
std::cout << compare(1, 0) << std::endl; // int 比較
std::vector<int> v1{1, 2, 3}, v2{4, 5, 6};
std::cout << compare(v1, v2) << std::endl; // vector 比較
std::cout << compare("girl", "lad") << std::endl; // 字串字面值比較
int a[] = {1, 2, 3, 4}, b[] = {1, 3, 4, 5};
std::cout << compare(a, b) << std::endl; // 陣列退化為指標,呼叫通用版本
return 0;
}
針對特定型別(如 C 風格字串)提供特化版本,可避免通用模板的不當行為(如指標比較而非內容比較)。善用 std::less 等函數物件提升泛用性與安全性。