Reputation: 1379
I've got class that inherite from template class. I would like to initialize pointer with template argument. How can I do that?
Algorithm.h:
#ifndef ALGORITHM_H
#define ALGORITHM_H
#include <iostream>
using namespace std;
template <typename T>
class Algorithm
{
protected:
T data;
T result; //(*)
int dataSize;
int resultSize;
public:
Algorithm(){}
Algorithm(T in, int inSize){
cout<<"Algorithm constructor!"<<endl;
data = in;
dataSize = inSize;
resultSize = dataSize;
result = new T; //(**)
for (int i = 0; i<this->resultSize; i++){
this->result[i] = 0;
cout<<"i: "<<i<<" *(this->result+i) = "<<this->result[i]<<endl;
}
}
#endif // ALGORITHM_H
Error is in (**) line:
/home/user/Projects/Algorithms/algorithm.h:23: error: cannot convert 'float**' to 'float*' in assignment result = new T; ^
I could change line (*) but it is not my favourite solution as it will be inconsistent with data - I would rather that to be so. So how can I initialize it to feel all result table with 0s then?
Upvotes: 1
Views: 1009
Reputation: 56557
If you don't want to change the (*) line to T* result
, then you can use std::remove_pointer<>
type trait (C++11 or later)
result = new typename std::remove_pointer<T>::type(); // a single element value-initialized
or (if you want an array, which is probably what you want)
result = new typename std::remove_pointer<T>::type [resultSize]; // array of resultSize elements
Finally, you can even value-initialize your array as
result = new typename std::remove_pointer<T>::type [resultSize]{}; // value-initialized array
However I find this solution awkward (to say the least), and it is probably much more clear if you use T* result
instead.
Upvotes: 3