Search code examples
c++templatesoperator-overloadingostream

Overloading ostream of vector template with iterator


Why I can't use iterator in ostream overloading?

If I use the same declaration using iterative approach it works.

Consider the following code:

template <class T>
class List {
    template <class U>
    friend ostream &operator<<(ostream &os, const List<U> &rhs);
private:
    vector<T> v;
};

template<class U>
ostream & operator<<(ostream & os, const List<U>& rhs)
{
    vector<U>::iterator it = rhs.v.begin();
    return os;
}

int main()
{
    List<int> list;
    cout << list << endl;
    return 0;
}

Solution

    1. Note that rhs is declared as reference to const, then rhs.v will be const too, then rhs.v.begin() will return a std::vector<U>::const_iterator, which can't be converted to std::vector<U>::iterator directly.

    2. You should use typename for dependent type names.

    So change it to

    typename vector<U>::const_iterator it = rhs.v.begin();
    

    BTW: void main() should be int main().