It's been a long time since I've done any C++ programming, but I've started back up and for the most part, things are going well. This problem however, has me stumped. Basically, I'm working with the wxWidgets library which provides a class "wxString" that works like a std::string except it also provides a stream-like overloaded << operator to concatenate non-string values at the end of the string. If, for example, you have a logging function that accepts a wxString it lets you do stuff like:
However when I try to define my own overloaded << operator for my own classes, things go wrong, but ONLY if I use it on a temporary object like above. Very much condensed (and non-wxWidgets specific) here's a complete program that causes the problem:Code:void Log(wxString const& in) {...} class Foo { int bar; public: LogBar() { Log(wxString("Bar is ") << bar << " right now."); } }
Which gives the error: (compiled with mingw32-g++ 3.4.5)Code:#include <iostream> #include <string> class StreamString { public: std::string buffer; StreamString() {}; }; class ThingToPutInStream { public: ThingToPutInStream() {} }; StreamString& operator << (StreamString & stream, ThingToPutInStream const& in) { stream.buffer += "ThingToPutInStream"; return stream; } void OutputStreamString(StreamString const& in) { std::cout << in.buffer; } int main() { { StreamString foo = StreamString(); OutputStreamString(foo << ThingToPutInStream()); } // these four lines compile normally OutputStreamString(StreamString() << ThingToPutInStream()); // this line fails to compile return 0; }
As far as I can tell the two bits of code in the main function are functionally equivalent; so why does one give me that error?Code:C:\Stuff\temptest.cpp||In function `int main()':| C:\Stuff\temptest.cpp|37|error: no match for 'operator<<' in 'StreamString() << ThingToPutInStream()'| C:\Stuff\temptest.cpp|19|note: candidates are: StreamString& operator<<(StreamString&, const ThingToPutInStream&)| ||=== Build finished: 1 errors, 0 warnings ===|
I'm obviously missing something here and I get the feeling it's something obvious, but I can't figure out. How do I get this operator to work with temporary objects?
Thanks in advance!



1Likes
LinkBack URL
About LinkBacks




CornedBee