1

So, i have class ArrayList, and inside, i have class iterator. I tried everything to make operator<< inside iterator class, to work with iterators, but nothing works. I tried with and without friend, in private and public, inline and outside the class, i have nothing else to try so if someone has some suggestion, feel free to say :D tyyy

also, i don't know does it have something with my problem, but ArrayList is template class

template <typename T>
std::ostream& operator<<(std::ostream& os, const ArrayList<T>::iterator & it)
{
    return os << *it;
}

template <typename T>
class ArrayList {
private:
    T* elements_;
    size_t size_;
    size_t capacity_;
public:
class iterator;
};

template <typename T>
class ArrayList<T>::iterator {
private:
    T* ptr_;
public:
friend std::ostream& operator<<(std::ostream&, const iterator&);
};
NutCracker
  • 10,520
  • 2
  • 39
  • 66
vlasaks
  • 13
  • 3

2 Answers2

1

ArrayList<T>::iterator is a dependent name so it needs to be preceeded with typename keyword like:

template <typename T>
std::ostream& operator<<(std::ostream& os, const typename ArrayList<T>::iterator & it) {
//                                               ^^^
    return os << *it;
}

and, of course, your operator<< overload should be defined after your class definition.

Demo

UPDATE

In order to resolve linking errors mentioned in the comments, try placing the operator<< overload body directly into the class body like:

template <typename T>
class ArrayList<T>::iterator {
private:
    T* ptr_;
public:
    friend std::ostream& operator<<(std::ostream& os, const iterator& it) {
        return os << *it;
    }
};
NutCracker
  • 10,520
  • 2
  • 39
  • 66
0

I would rather consider having operator *

template <typename T> class ArrayList {
private:
    T* elements_;
    size_t size_;
    size_t capacity_;
public:
    class iterator {
    private:
        T* ptr_;
    public:
        T operator *() {return *ptr_;}
    };
};

Now the operator << will work naturally for any type T that has operator defined, so you don't have to define it by yourself:

cout<< *it<< endl;

You will define the operator << only on typename T if it does not have operator defined. Normally you will not define it for int, char, string and so on.

armagedescu
  • 1,505
  • 2
  • 19
  • 25
  • but i need operator << to work directly with iterator – vlasaks Apr 06 '20 at 07:21
  • How exactly you need it to work directly with iterator? What exactly the operator has to do with iterator? – armagedescu Apr 06 '20 at 07:23
  • @vlasaks the iterator implements the paradigm of pointer. A pointer need such operators as ++ -- * -> + .... But streaming a pointer with << is not a correct operation with a pointer. – armagedescu Apr 06 '20 at 07:28
  • @vlasaks You have to see what the iterators do. The std containers iterators do not implement such an operator. – armagedescu Apr 06 '20 at 07:30