[英]couldn't deduce template parameter ‘looptype’
#include<cstdlib>
#include<iostream>
#include<math.h>
#include<string>
using namespace std;
class getAverage{
public:
template<class add>
add computeAverage(add input[], int nosOfElem){
add sum = add();//calling default constructor to initialise it.
for(int index=0;index<=nosOfElem;++index){
sum += input[index];
}
return double(sum)/nosOfElem;
}
template<class looptype>
looptype* returnArray(int sizeOfArray){
looptype* inputArray= (int*)malloc(sizeof(int)*sizeOfArray);
for(int index=0;index<=sizeOfArray;++index){
inputArray[index]=index;//=rand() % sizeOfArray;
}
return inputArray;
}
};
int main(){
int sizeOfArray=2;
int inputArray;
getAverage gA;
int* x= gA.returnArray(sizeOfArray);
for(int index=0;index<=2;++index){
cout<<x[index];
}
cout<<endl;
cout<<gA.computeAverage(x,sizeOfArray);
free(x);
return 0;
}
I want to create a template function through which I can create dynamic arrays of different type(Int,long,string ..etc.). 我想创建一个模板函数,通过它可以创建不同类型的动态数组(Int,long,string等)。 I tried doing it,and realised that the "looptype" never gets the type value.
我尝试这样做,并意识到“ looptype”从不获取类型值。 Can someone suggest a way to do this.
有人可以建议一种方法来做到这一点。
Thanks 谢谢
template<class looptype>
looptype* returnArray(int sizeOfArray){
looptype* inputArray= (int*)malloc(sizeof(int)*sizeOfArray);
for(int index=0;index<=sizeOfArray;++index){
inputArray[index]=index;//=rand() % sizeOfArray;
}
return inputArray;
}
template parameters can only be deduced from the function-template arguments. 模板参数只能从function-template参数推导出。 Here the only argument your function template takes is
sizeOfArray
which is an int
. 这里,函数模板采用的唯一参数是
sizeOfArray
,它是一个int
。 How does the compiler know what typename looptype
is? 编译器如何知道什么是
typename looptype
类型? Since it cannot be deduced, you have to explicitly specify it. 由于无法推断出它,因此必须明确指定它。
int* x= gA.returnArray<int>(sizeOfArray);
rather than: 而不是:
int* x= gA.returnArray(sizeOfArray);
BTW, what's the point of have a template parameter looptype
when I know it can only be an int
as sold by this line of your code: 顺便说一句,当我知道它只能是此行代码所出售的
int
时,具有模板参数looptype
有什么意义:
...
looptype* inputArray= (int*)malloc(sizeof(int)*sizeOfArray);
...
Your use of malloc
is scary. 您对
malloc
使用令人恐惧。 For virtually same performance, you are making simple tasks complicated. 为了获得几乎相同的性能,您使简单的任务变得复杂。 Prefer
std::vector<int>
or worse case std::unique_ptr<int[]>
. 更喜欢
std::vector<int>
或更糟糕的情况是std::unique_ptr<int[]>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.