2017-02-10 120 views
0
#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; 
} 

我想创建一个模板函数,通过它我可以创建不同类型的动态数组(int,long,string ..等等)。我试过这样做,并意识到“looptype”永远不会获得类型值。有人可以建议一种方法来做到这一点。无法推导出模板参数'looptype'

感谢

+1

为什么不'自动?还有什么'malloc'在C++代码中做什么?绝对最少使用'new []',但更好的办法是使用'std :: vector',这是一个容器,它有方法来产生大小,而不必传递C风格的指针和大小对。 – tadman

回答

1
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; 
} 

模板参数只能从函数模板参数中推演出来。这里函数模板的唯一参数是sizeOfArray这是一个int。编译器如何知道typename looptype是什么?由于无法推断,因此必须明确指定它。

int* x= gA.returnArray<int>(sizeOfArray); 

而不是:

int* x= gA.returnArray(sizeOfArray); 

顺便说一句,什么是有一个模板参数looptype当我知道这只能是一个int由这行代码的卖出点:

... 
looptype* inputArray= (int*)malloc(sizeof(int)*sizeOfArray); 
... 

您使用malloc是可怕的。对于几乎相同的性能,您将简单的任务变得复杂。首选std::vector<int>或更坏的情况std::unique_ptr<int[]>