C++函数模板的一个匹配问题
在学习C++函数模板一节时,遇到了这样一个问题:
#include <iostream>
using namespace std;
struct debt{
char name[40];
double debts;
};
template <class T>
double SumArray(T* a[],int n)
{
double sum=0;
for(int i=0;i<n;i++)
sum+=*a[i];
return sum;
}
template<class T>
T SumArray(const T a[],int n)
{
T sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum;
}
int main()
{
int things[9]{1,2,3,4,5,6,7,8,9};
cout<<SumArray(things,9)<<endl;
debt ps[4]={"name1",1.1,"name2",2.2,"name3",3.3,"name4",3.3};
double *pt[4];
for(int i=0;i<4;i++)
pt[i]=&ps[i].debts;
cout<<SumArray(pt,4)<<endl;
while(cin.get()!=EOF);
return 0;
}
如上代码能够正常运行,但是当在两个模板函数参数前面加上const限定符便会出错:
template <class T>
double SumArray(const T* a[], int n);
template<class T>
T SumArray( T a[], int n);
这样会存在 ld returned 1 exit status
这样的错误。
template <class T>
double SumArray(const T* a[], int n);
template<class T>
T SumArray(const T a[], int n);
这样会存在这样的问题:invalid operands of types 'double*' and 'double*' to binary 'operator+'
根据这个错误的意思是不是函数的调用匹配到了第一个模板函数??为什么会匹配到第一个?
两个函数第一个只需要添加const
把T转化为double即可完成匹配,第二个函数需要把T转化为double *
这种情况怎么匹配函数?如果说这两个转化同样具体不知道使用哪个而出错,那么,对于上面第二种错误,第二个函数在把T转化为double *
时还需要在前面添加const
限定符,应该是第一个函数更具体才对吧