简体   繁体   中英

pointer initialization with template typename

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?

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM