您的位置:首页 > 编程语言 > C语言/C++

C++ - 函数模板(function template) 的 重载(overload) 详解 及 代码

2013-11-28 18:29 946 查看

函数模板(function template) 的 重载(overload) 详解 及 代码

本文地址: http://blog.csdn.net/caroline_wendy/article/details/17010031

函数模板(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"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息