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

函数模板(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"


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ElminsterAumar

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值