gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:03:33 25 4
gpt4 key购买 nike

我是 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 >matching function for call to ‘findElement(long int [3], int, long > >unsigned int)’| note: candidate: >template int findElement(T1*, T1, long int)| note: template argument deduction/substitution failed:| /home/robin/Dokumente/CPP/Labor2/Aufg2/aufg2b/main.cpp|19|note: deduced conflicting types for parameter ‘T1’ (‘long int’ and ‘int’)| ||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

最佳答案

问题是

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

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

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

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

您可以通过使 15133 成为 long 整型文字来修复它,例如

findElement(arr2,15133L,sizeof(arr2)/sizeof(long int));
^ L for long

关于c++ - C++ 中的模板仅在 long 数据类型上出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37077354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com