简体   繁体   中英

allocation of incomplete type 'T' c++

I am implementing a dynamic array in c++ using a raw pointer. I'm new to using templates. I decided to split the class into two .hpp and .cpp files also for the sake of practice. I'm getting the following compilation error in the source file when initializing the T array:

"Allocation of incomplete type 'T'"

Here is the header file:

template <class T>
class DynArray {

public:
    DynArray(); //default constructor
private:
    T * array; //internal array
    int memsize; //number of allocated memory slots
    int t_size; //number of occupied memory slots
};

Here is the source file:

template <>
DynArray<class T>::DynArray() {
    memsize = 2;
    t_size = 0;
    array = new T[memsize];

}

I'm not comfortable with what I'm doing here in the source file. I basically followed what my IDE (xcode) told me to do, but something feels wrong about creating a specialized template here. What is a correct way of doing this?

Please read this as a start point Why can templates only be implemented in the header file?

Regarding the error Allocation of incomplete type 'T' . Please look carefully at the code

template <>
DynArray<class T>::DynArray()

template there does not introduce type T . The type class T is introduced in the second line, it is mentioned first time there. As you may know class T without template is a forward declaration and is an incomplete type, its size is unknown and new can not allocate memory of unknown size. The proper template class member should be declared like this

template <class T>
DynArray<T>::DynArray()

It is correct syntactically, but not practically, read the article mentioned above.

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