C++ - 函数模板定制(function template specialization) 详解 及 代码

函数模板定制(function template specialization) 详解 及 代码

 

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

 

函数模板定制可以解决特定的模板参数, 需要特定的函数方法去实现;

注意函数模板定制是实例化模板, 而不是模板的重载; 

非模板函数(nontemplate function)存在时, 当匹配度相同时, 优先使用非模板函数;

比较(compare)函数, 比较字符串(char*)类型, 不能通过判断地址去比较, 应该使用strcmp()函数, 需要定制函数模板;

函数模板定制需要使用 "template<>", 空的尖括号表明 提供的模板实参支持原版本的所有模板形参;

代码:

 

/*
 * CppPrimer.cpp
 *
 *  Created on: 2013.12.9
 *      Author: Caroline
 */

/*eclipse cdt, gcc 4.8.1*/

#include <iostream>
#include <vector>
#include <cstring>

using namespace std;

template <typename T>
bool compare (const T& t1, const T& t2)
{
	std::cout << "first version" << std::endl;
	return (t1<t2) ? true : false;
}

//函数模板定制
template<>
bool compare (const char* const &p1, const char* const &p2)
{
	std::cout << "third version" << std::endl;
	return strcmp(p1, p2);
}

//有非模板优先使用非模板
/*bool compare (const char* const &p1, const char* const &p2)
{
	std::cout << "forth version" << std::endl;
	return strcmp(p1, p2);
}*/

//处理字面类型的比较
template<unsigned N, unsigned M>
bool compare (const char (&p1)[N], const char (&p2)[M])
{
	std::cout << "second version" << std::endl;
	return strcmp(p1, p2);
}

int main(void)
{
	const char* w("Wendy");
	const char* c("Caroline");
	//没有函数模板定制, 调用第一个版本, 因为指针不能转换为数组的引用
	if(compare(c, w)) {
		std::cout << "Caroline is long." << std::endl;
	} else {
		std::cout << "Wendy is long." << std::endl;
	}

	if(compare("Caroline", "Wendy")) {
		std::cout << "Caroline is long." << std::endl;
	} else {
		std::cout << "Wendy is long." << std::endl;
	}

	return 0;
}
	std::cout << "forth version" << std::endl;
	return strcmp(p1, p2);
}*/

//处理字面类型的比较
template<unsigned N, unsigned M>
bool compare (const char (&p1)[N], const char (&p2)[M])
{
	std::cout << "second version" << std::endl;
	return strcmp(p1, p2);
}

int main(void)
{
	const char* w("Wendy");
	const char* c("Caroline");
	//没有函数模板定制, 调用第一个版本, 因为指针不能转换为数组的引用
	if(compare(c, w)) {
		std::cout << "Caroline is long." << std::endl;
	} else {
		std::cout << "Wendy is long." << std::endl;
	}

	if(compare("Caroline", "Wendy")) {
		std::cout << "Caroline is long." << std::endl;
	} else {
		std::cout << "Wendy is long." << std::endl;
	}

	return 0;
}


输出:

 

 

third version
Caroline is long.
second version
Caroline is long.

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

ElminsterAumar

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

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

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

打赏作者

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

抵扣说明:

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

余额充值