函數模板(function template)重載, 即實例化特定的模板, 確定T的類型, 選擇匹配度最高的一個;
需要注意傳遞的具體類型, 如傳遞的是"&s", 則表示"string* t = &s", 即實際匹配的類型為"string* t";
當非函數模板和函數模板匹配度相同時, 優先選擇非函數模板;
調用模板時, 一定要注意順序, 或者提前聲明, 以保證可以找到函數模板, 進行實例化;
具體參見代碼注釋, 代碼如下:
/*
* 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();
}
/*非模板函數*/
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; //調用第一個 / 優先調用非模板
//&s, 即 string* s = &s, string* t = const T &t, 即 T->string*
// string* t = T* t, 即 T->string; 所以選擇第二個
std::cout << debug_rep (&s) << std::endl; //調用第二個
const std::string *sp = &s;
std::cout << debug_rep (sp) << std::endl; //調用第二個
//調用第二個, 只傳遞首字母; 包含char版本, 右值調用const
std::cout << debug_rep("hello world") << std::endl;
return 0;
}
輸出:
"hi" pointer: 0x22fec4 hi pointer: 0x22fec4 hi const "hello world"
作者:csdn博客 Spike_King