I want to overload ostream& operator << so that it prints content of whatever container I want. I wrote something like this:
It works. However, it'd be nice to actually have these spaces between numbers. There's the problem: when I uncomment the code (and remove ++it from the for loop), the compilers gives me a bunch of messages with the "main" reading:Code:#include <iostream> #include <list> #include <set> template <class T> ostream& operator << (ostream& strm, T l) { for (class T::iterator it = l.begin(); it != l.end();++it) { strm << *it; // if (++it != l.end()) // strm << " "; } return strm; } int main() { list<int> l; int t[] = {1,2,3,-1,-2,-3}; l.insert(l.begin(), t, t + 6); cout << l; set<int> s; s.insert(l.begin(), l.end()); cout << s; }
Does anyone have any idea why does it not work? (it seems like << isn't overloaded for const char *, but simple cout << " "; works, so...)Code:stl_test.cpp: In function ‘std::ostream& operator<<(std::ostream&, T)’: stl_test.cpp:19: error: ambiguous overload for ‘operator<<’ in ‘strm << " "’
I use g++ 4.4.5




Reply With Quote
