C++中函数模板定制(function template specialization) 详解
函数模板定制可以办理特定的模板参数, 需要特定的函数要领去实现;
留意函数模板定制是实例化模板, 而不是模板的重载;
有非模板函数(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)
{
<span style="white-space:pre"> </span>std::cout << "forth version" << std::endl;
<span style="white-space:pre"> </span>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.
作者:csdn博客 Spike_King