简体   繁体   中英

Errors trying to overload template class friend << operator

Trying to code a better version of array type i have run into an issue. For some reason the declaration doesnt work. It throws at me bunch of weird errors. Tried looking up the issue but havent found anything so far. Here is the code:

Template <class T>
class SafeArray {

private:
    int size;
    int elements;
    int index;
    T* arr;

public:

    SafeArray(int n);
    ~SafeArray();
    void push_back(T item);
    void resize(int size);
    friend std::ostream& operator << (std::ostream& os, const SafeArray<T>& ar)


};

And the implementation outside the class:

template<class T>
std::ostream& operator << <T> (std::ostream& os, const SafeArray<T> & arr) {

    for (int i = 0; i < arr.elements; i++) {
        std::cout << arr[i] << " ";
    }

    std::cout << std::endl;

    return os;
}

If you want friend template , the friend declaration should be

template <class T>
class SafeArray {
    ...
    template<class X>
    friend std::ostream& operator << (std::ostream& os, const SafeArray<X>& ar);
};

the implementation should be

template<class T>
std::ostream& operator << (std::ostream& os, const SafeArray<T> & arr) {
    ...
}

LIVE

BTW: In the implementation of operator<< , I think std::cout << arr[i] << " "; should be std::cout << arr.arr[i] << " "; .

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