#include<iostream.h>
template<typename T>
void func(const int &t)
{
cout<<t+100<<endl;
}
template<typename T>
void func(const T &t)
{
cout<<t<<endl;
}
int main()
{
func(10.3);
func(1000);
return 0;
}
程序运行结果:
10.3 1000
如果上述函数改为
#include<iostream.h>
void func(const int &t)
{
cout<<t+100<<endl;
}
template<typename T>
void func(const T &t)
{
cout<<t<<endl;
}
int main()
{
func(10.3);
func(1000);
return 0;
}则程序的运行结果为:
10.3 1100
分析:
第一种情况
编译器使用模板函数来进行编译;
然而,编译器使用模板函数来进行编译,为什么使用第2个模板函数匹配,为什么不用第一个呢?因为第一个模板函数参数里没有T类型的参数,编译器无法为第一个模板函数推导模板参数,就是说它不知道在这个函数里面T应该被推导为何种类型,所以只能使用第二个函数,如果这么写:
func<double>(10.3);
func<int>(1000);//显式给出模板类型
就会发现结果是:10.3 1100
第二种情况
func(整数)匹配,优先调用函数。
也就是说,在满足函数匹配的情况下,编译器优先使用函数匹配编译,函数不能匹配情况下,再使用模板匹配。