mercredi 26 juillet 2017

Overloading operator<<() for stl containers

I am trying to overload operator<<() (i.e. inserter operator) for stl containers (e.g vector, list, array) (i.e. any container that support range-based for loop and whose value_type also has overload for operator<<()). I have written the following template function

template <template <class...> class TT, class ...T>
ostream& operator<<(ostream& out, const TT<T...>& c)
{
    out << "[ ";

    for(auto x : c)
    {
        out << x << " ";
    }

    out << "]";
}

It works for vector and list. But it gives error when I try to call it for array

int main()
{
    vector<int> v{1, 2, 3};
    list<double> ld = {1.2, 2.5, 3.3};
    array<int, 3> aa = {1, 2, 3};

    cout << v << endl;  // okay
    cout << ld << endl; // okay
    cout << aa << endl; // error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’
                        // cout << aa << endl;
                        //         ^
}

Why it does not work for array? Is there any work around to overcome this problem?

I have searched in the internet and SO to find if there is a way to overload operator<<() for stl containers. I have read answers in overloading << operator for c++ stl containers, but it does not answer my question. And answers in Pretty-print C++ STL containers seems complecated to me.

g++ version: g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4

Compile command: g++ -std=c++11

Aucun commentaire:

Enregistrer un commentaire