mintbox
mintbox

Reputation: 167

Use of class template requires template arguments

Hi I'm still wondering why I'm getting this error message :

Use of class template 'Array' requires template arguments

Header :

#ifndef Array_h
#define Array_h


template< typename T>
class Array
{
public:
    Array(int = 5);
    Array( const Array &);

    const Array &operator=(Array &);
    T &operator[](int);
    T operator[](int) const;

    // getters and setters
    int getSize() const;
    void setSize(int);

    ~Array();

private:
    int size;
    T *ptr;

    bool checkRange(int);


};

#endif

CPP file

template< typename T >
const Array &Array< T >::operator=(Array &other)
{
    if( &other != this)
    {
        if( other.getSize != this->size)
        {
            delete [] ptr;
            size = other.getSize;
            ptr = new T[size];
        }

        for ( int i = 0; i < size; i++)
        {
            ptr[i] = other[i];
        }
    }
    return *this;
}

Problem seems to do with returning a const reference to object.

Thanks.

Upvotes: 3

Views: 12816

Answers (1)

T.C.
T.C.

Reputation: 137414

Before the compiler sees Array<T>::, it doesn't know that you are defining a member of the class template, and therefore you cannot use the injected-class-name Array as shorthand for Array<T>. You'll need to write const Array<T> &.

And you got constness backwards in your assignment operator. It should take a const reference and return a non-const one.

Also, Why can templates only be implemented in the header file?

Upvotes: 6

Related Questions