函數模板重載本質是實例化特定模板,確定 T 型別,選擇匹配度最高者。關鍵在於理解實參型別如何映射至模板參數。
&s(string 物件位址) → 實際匹配 string* t → 推導 T = string*/*
* cppprimer.cpp - 函數模板重載範例
* Created on: 2013.11.28
* Author: Caroline
* eclipse cdt, gcc 4.8.1
*/
#include <iostream>
#include <sstream>
#include <string>
#include <utility>
using namespace std;
// 通用模板版本
template <typename T>
std::string debug_rep(const T &t) {
std::ostringstream ret;
ret << t;
return ret.str();
}
// 指標版本
template <typename T>
std::string debug_rep(T *p) {
std::ostringstream ret;
ret << "pointer: " << p;
if (p) ret << " " << debug_rep(*p);
else ret << " null pointer";
return ret.str();
}
// 非模板版本:string 專用
std::string debug_rep(const string &s) {
return '"' + s + '"';
}
// char* 重載
std::string debug_rep(char *p) {
std::cout << "plain ";
return debug_rep(std::string(p));
}
// const char* 重載
std::string debug_rep(const char *p) {
std::cout << "const ";
return debug_rep(std::string(p)); // 呼叫通用模板
}
int main(void) {
std::string s("hi");
std::cout << debug_rep(s) << std::endl; // "hi" - 非模板優先
std::cout << debug_rep(&s) << std::endl; // pointer: 0x... hi - 指標模板
const std::string *sp = &s;
std::cout << debug_rep(sp) << std::endl; // pointer: 0x... hi - 指標模板
std::cout << debug_rep("hello world") << std::endl; // const "hello world" - const char* 重載
return 0;
}
"hi" pointer: 0x22fec4 hi pointer: 0x22fec4 hi const "hello world"
template<>)const char* → std::string)設計重載組時,應確保非模板版本處理特殊情況,模板版本提供通用支援,避免模糊匹配導致編譯錯誤。