_南明_离火_ 2022-06-21 09:00 采纳率: 100%
浏览 42
已结题

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

  • 写回答

2条回答 默认 最新

  • 关注

    由于不是引用类型,数组 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 非常难以理解,难以维护,如果能改程序的设计,尽量不要这么用。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 6月30日
  • 已采纳回答 6月22日
  • 修改了问题 6月21日
  • 创建了问题 6月21日

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。