I have a function that prints them to an ostream:
void PrintObject(Object & obj, ostream & out)
{
out << ">";
PrintSubObject(obj.customSubObject1, out); // I'd like to replace this with: out << obj.customSubObject1;
out << "(";
PrintSubObject(obj.customSubObject2, out); // I'd like to replace this with: out << obj.customSubObject2;
out << ")";
out << endl;
}
This works great for printing to anything that's a subclass of ostream, for example files (ofstream) or string streams (ostringstream).
Now, suppose I want to print the same objects to another target, for example to the screen via an OpenGL window and a function that renders text on screen.
Would it be a good idea to do this by deriving a class from std::ostream and using that approach, or is it wrong in some way? I'd like to avoid having a DrawObject() function that has the same code, except out is an OpenGLTextPrinterStream instance.
I've tried doing it, but it's not easy. Just overriding the operator<<() functions in my ostream subclass doesn't work, because they're not virtual functions and never get called.
Based on this post, it seems a proper approach would be to use a custom streambuf subclass. Is this what I should be doing?
When I take that approach, my problem is that streambuf is really designed to work with character-based streams, but what I really want to do is process the entire object at once, rather than having to break it down into characters and then re-assembling it.
It'd be great if I could just do this...
class OpenGLTextPrinterStream {
operator << (CustomSubObject subobj)
{
// Render CustomSubObject on screen
}
}
Any suggestions? Am I shoehorning ostream into something it shouldn't be used for, or if this is indeed a good approach, how do I go about implementing it?