首先我们还是以一个例子来开始,我定义了一个如下的函数模板用来实现,两个对象的比较功能:
点击(此处)折叠或打开
-
template<typename T> int compare(const T &first, const T &second)
-
{
-
return first > second ? first : second;
- }
点击(此处)折叠或打开
-
template<> //全特化的表示方法
-
int compare
( const char* const &first, const char* const &second)
-
{
-
return (strcmp(first, second) >= 0) ? first : second ;
- }
点击(此处)折叠或打开
-
int compare<const char*>(const char* const &first, const char* const &second)
-
{
-
return (strcmp(first, second) >= 0) ? first : second ;
- }
点击(此处)折叠或打开
- 错误: 特例化成员‘::compare<const char*>’需要‘template<>’语法
点击(此处)折叠或打开
-
int compare(const char* const &first, const char* const &second)
-
{
-
return strcmp(first, second);
-
}
-
-
template<>
-
int compare(const char* const &first, const char* const &second)
-
{
-
return strcmp(first, second);
- }
我这个时候实际测试了一下,这两个函数,为了加以区别我们修改了一下第一个函数中实现我们改成下面:
点击(此处)折叠或打开
-
int compare<const char*>(const char* const &first, const char* const &second)
-
{
-
return 0 - strcmp(first, second);
- }
点击(此处)折叠或打开
-
int main()
-
{
-
-
int a = 10;
-
int b = 2;
-
const char *p1 = "dang";
-
const char *p2 = "dao";
-
cout << "resulst strcmp: " << compare(p1, p2) << endl;
-
cout << "result int: " << compare(a, b) << endl;
-
return 0;
- }
点击(此处)折叠或打开
-
resulst strcmp: 1
- result int: 10
原因到底什么呢?
是这样的,在c++之中,是允许用户重载一个函数的,所谓函数的重载,就是我们可以用同一个函数名,通过改变传入该函数的实参,来定义不同的函数实现。更为强大的一点是,c++也允许我们重载一个函数模板!!
c++中确定函数调用的步骤如下:
(1)为这个函数名建立一个候选函数的集合,包括:
a、与被调用函数重名的任意普通的函数。
b、任意函数模板的实例化,通过模板实参的推断匹配
(2)首先是查找哪些普通函数是可行的(确定这个普通函数是否可行,必须是传入实参和函数形参类型的精确匹配,经过类型转换匹配的不符合要求),然后才是查找模板中的实例来匹配。
所以我们会发现,在本例中我们陋写完成的函数特化,实际上是对于模板函数的重载,重载函数会优先于模板在函数调用时进行匹配,无论是原来的模板还是我们特化之后的模板,他们优先级都是要低于我们重载的函数,当然重载函数匹配需要形参和传入实参的完全匹配。