C++函数模板的一个匹配问题

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限定符,应该是第一个函数更具体才对吧

由于不是引用类型,数组 T * a[ ] 退化成指针 T ** a,只有 double * const *a 可以接受一个 double ** , const double ** 则无法接受。


template <class T> auto SumArray(T *const a[], int n) -> double
{
    double sum = 0;
    for (int i = 0; i < n; i++)
    {
        sum += *a[i];
    }
    return sum;
}

如果不想变模板,可以改指针数组:

    const double *pt[4];

嵌套指针加 const 非常难以理解,难以维护,如果能改程序的设计,尽量不要这么用。

报错都是因为T被推导成了double *类型,然后定义了T sum=0;等价于double* sum=0;,执行了sum+=a[i];的运算
匹配规则的话的找下资料,我忘了,C++Prime第五版的函数模板那两章里面有