I have a simple GUI program that uses a custom stringstream to redirect output from the console to a text field in the GUI (under some circumstances). currently. the window redraws any time I hit enter, but it’s possible that output could be generated at other times. Is there a way to register a function with the stringstream that gets executed every time the << operator is used on the stream?
NOTE
I should have pointed out that I cannot use C++11 in my solution. the machines on which this will be compiled and run will not have c++11 available.
Personally, I wouldn’t use an
std::ostringstream(or even anstd::stringstream) for this at all! Instead, I would create my own stream buffer taking care of sending the data to the GUI. That is, I’d overwritestd::streambuf::overflow()andstd::streambuf::sync()to send the current data to the GUI. To also make sure that any output is sent immediately, I’d set up anstd::ostreamto havestd::ios_base::unitbufset. Actually, sending the changes to a function is quite simple, i.e., I’ll implement this:A fair chunk of the above code is actually unrelated to the task at hand: it implements a primitive version of
std::function<void(std::string)>in case C++2011 can’t be used.If you don’t want quite as many calls, you can turn off
std::ios_base::unitbufand only sent the data upon flushing the stream, e.g. usingstd::flush(yes, I know aboutstd::endlbut it unfortunately is typically misused to I strongly recommend to get rid of it and usestd::flushwhere a flush is really meant).