Search code examples
c++templatesoperator-overloadingmanipulators

Templates, no match for 'operator<<' in 'out << "("'


I'm trying to overload << operator for template and I'm getting this error.

What I'm trying to achieve is overloaded operator << that will provide opening bracket, all tab items separeted by "," and closing bracket to 'out'.

Here is part of my code:

template <typename T>
class arry{
    T *tab;
    int n;
public:
    arry(T *t, int x) : n(x),tab(t){};
    friend std::ostream & operator << (const std::ostream & out, const arry<T> & t)
    {
        out << "(";
        for(int i=0;i<t.n;i++){
            out << t.tab[i];
            if(i < t.n-1)
                out << ", ";
        }
        out << ")";
        return out;
    }
};

And the worst part is that my build log provides me 230 error lines and at this point I'm a little confused.


Solution

  • The operator is meant to modify the stream, so the first parameter cannot be const reference. Change it to

    friend std::ostream & operator << (std::ostream & out, const arry& t)