Passing extra arguments to output operator

I usually implement the output operator for a class, operator<<().
I find it useful for debugging and regression testing purposes.
Occasionally when defining a class hierarchy with polymorphism in mind
I’ll instead define a virtual print() method.

Here’s the typical implementation:

So everything is great except… I now want to pass that extra
argument. I could write the following ugly code:

Instead, I’m going to follow the example from <iomanip> and define a struct
that saves the arguments and then define an output operator for that
struct. The following code makes it so you can write the above as:

Here is the implementation of that. This expects the class to implement a method print() that takes a std::ostream and a second argument. It’s pretty easy to extend this to a print() that takes a third argument.

Leave a Reply

Your email address will not be published. Required fields are marked *