C++中函数模板(function template) 的 重载(overload) 详解
函数模板(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