C ++中的模板仅在long数据类型上出错

时间:2016-05-06 16:34:03

标签: c++

我是C ++的新手,有人可以帮我解决这个错误吗?

#include <iostream>

using namespace std;

template<typename T1>
int findElement(T1 field[],T1 element,long int indx);

template<typename T2>
double getAverage(T2 field[],long int indx);
int main()
{
       int arr1[] = {1,1,2,1,1,2,1,2,3};
  long int arr2[] = {19133,15133,13213};
    double arr3[] = {1,1,1,2.9,0,0,0,0};

  findElement(arr1,2,sizeof(arr1)/sizeof(int));
  cout << "Average =" << getAverage(arr1,sizeof(arr1)/sizeof(int)) << endl;
  findElement(arr2,15133,sizeof(arr2)/sizeof(long int)); //<=== Error
  cout << "Average =" << getAverage(arr2,sizeof(arr2)/sizeof(long int)) << endl;
  findElement(arr3,2.9,sizeof(arr3)/sizeof(double));
  cout << "Average ="  << getAverage(arr3,sizeof(arr3)/sizeof(double)) << endl;
  return 0;
}

template<typename T1>
int findElement(T1 field[],T1 element,long int indx)
{
      int pos = -1;
  cout << " searching for " << element << " ...";
  for(int i=0;i<indx;i++)
  {
      if(element==field[i])
      {
          pos = i;
      }
   }
   if(pos>0) cout << " found! Position is : " << pos << endl;
   else      cout << " no found!" << endl;
   return pos;
}

template<typename T2>
double getAverage(T2 field[],long int indx)
{
   int sum = 0;
   for(int i=0;i<indx;i++)
       sum += field[i];
   return static_cast<double>(sum)/static_cast<double>(indx);
}
  

| 19 | error:no&gt;匹配函数用于调用'findElement(long int [3],int,long&gt;&gt; unsigned int)'|   注意:候选人:&gt;模板int findElement(T1 *,T1,long int)|   注意:模板参数扣除/替换失败:|   /home/robin/Dokumente/CPP/Labor2/Aufg2/aufg2b/main.cpp|19|note:推导出参数'T1'的冲突类型('long int'和'int')|   || ===构建失败:1个错误,0个警告(0分钟,0秒(秒))=== |

1 个答案:

答案 0 :(得分:3)

问题在于

template<typename T1>
int findElement(T1 field[],T1 element,long int indx);

要求fieldelement具有相同的类型。当你打电话

findElement(arr2,15133,sizeof(arr2)/sizeof(long int));

arr2long15133是整数文字,类型为int。由于longint不是相同的类型模板,因此推论失败并且您得到编译器错误。请注意编译器在模板参数推导期间没有转换。如果在该步骤中类型不匹配,则不会使用该模板。

您可以通过15133 long整数文字

来修复它
findElement(arr2,15133L,sizeof(arr2)/sizeof(long int));
                      ^ L for long