#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.). I tried doing it,and realised that the "looptype" never gets the type value. 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. Here the only argument your function template takes is sizeOfArray
which is an int
. How does the compiler know what typename looptype
is? 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:
...
looptype* inputArray= (int*)malloc(sizeof(int)*sizeOfArray);
...
Your use of malloc
is scary. For virtually same performance, you are making simple tasks complicated. Prefer std::vector<int>
or worse case std::unique_ptr<int[]>
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.