简体   繁体   English

使用模板typename初始化指针

[英]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: 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; /home/user/Projects/Algorithms/algorithm.h:23:错误:在赋值结果= new T时无法将'float **'转换为'float *'; ^ ^

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? 那么如何初始化它以感觉所有结果表为0?

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) 如果您不想将(*)行更改为T* result ,则可以使用std::remove_pointer<>类型特征(C ++ 11或更高版本)

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. 但是我发现这个解决方案很尴尬(至少可以说),如果你使用T* result可能会更清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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