0

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;
}
Jacob G.
  • 28,856
  • 5
  • 62
  • 116
TomatoLV
  • 67
  • 1
  • 6

1 Answers1

0

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] << " ";.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • I have done so but i still get errors: error C3646: 'T': unknown override specifier note: see reference to class template instantiation 'SafeArray' being compiled error C2988: unrecognizable template declaration/definition error C2059: syntax error: '&' error C2334: unexpected token(s) preceding '{'; skipping apparent function body – TomatoLV Apr 08 '18 at 00:37
  • @TomatoLV There're some other issues, see the live demo I posted. – songyuanyao Apr 08 '18 at 00:41