C++: Overloading << for streams; namespace std
I was playing around with STL's ostream_iterator and tried to use it to output non-trivial types by overloading the stream insertion operator. I kept getting template errors in the iterator's system header claiming that it couldn't resolve the operator call, even though I defined it in my main.cpp before I included the header. Eventually I tried surrounding the definition with namespace std {} and that fixed it.
What I don't understand is why the header could not see my function when it was outside of std and in the global scope. The only reason I can think of is that another standard overloaded operator definition inside std took precedence, even though it didn't fit well at all.
Strangely enough, when I defined my operator within std, I could place the definition at any point I liked in my file, even after my main function without a prototype.
Code:
namespace std { // would not work when declared in global scope
ostream& operator<< (ostream& os, const pair<int, int>& arg)
{
os << "(" << arg.first << "," << arg.second << ")";
}
}
...
ostream_iterator< pair<int, int> > oi(cout, " "); // construct ostream_iterator to write to cout when assigned a pair of ints
*oi = pair<int, int>(1, 2);