Results 1 to 3 of 3
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 ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
- 10-19-2005 #1Linux Newbie
- Join Date
- Nov 2004
- Location
- New York
- Posts
- 150
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);
\"Nifty News Fifty: When news breaks, we give you the pieces.\" - Sluggy Freelance
- 10-19-2005 #2
I think the reason is that the compiler knows what namespace it's supposed to be using, and hence looks inside that first for a matching method. Even though it's a poor match, it still comes out as a match, and so gets used in preference to anything in the global scope.
Linux user #126863 - see http://linuxcounter.net/
- 10-19-2005 #3Linux Newbie
- Join Date
- Nov 2004
- Location
- New York
- Posts
- 150
The dummy overload confuses the compiler into not realizing there is a choice outside of the namespaces aaa and std. If I move the dummy to global scope, there's no problem.Code:std::ostream& operator+ (std::ostream& os, const std::pair<int, int>& arg) { os << "(" << arg.first << "," << arg.second << ")"; } namespace aaa { std::ostream& operator+ (std::ostream& os, int i) {return os;} // dummy overload void test () { std::cout + std::pair<int, int>(1, 2); }}
Guess I'm going to be looking up the overload resolution rules. Sigh... it seems kind of inelegant that to use some of the features of the standard library, you have to invade its namespace.\"Nifty News Fifty: When news breaks, we give you the pieces.\" - Sluggy Freelance


Reply With Quote
