I’d like to implement a custom manipulator for ostream to do some manipulation on the next item being inserted into the stream. For example, let’s say I have a custom manipulator quote:
std::ostringstream os; std::string name('Joe'); os << 'SELECT * FROM customers WHERE name = ' << quote << name;
The manipulator quote will quote name to produce:
SELECT * FROM customers WHERE name = 'Joe'
How do I go about accomplishing that? Thanks.
It’s particularly difficult to add a manipulator to a C++ stream, as one has no control of how the manipulator is used. One can imbue a new locale into a stream, which has a facet installed that controls how numbers are printed – but not how strings are output. And then the problem would still be how to store the quoting state safely into the stream.
Strings are output using an operator defined in the
stdnamespace. If you want to change the way those are printed, yet keeping the look of manipulators, you can create a proxy class:Which would be suitable to be used for
ostream. If you want to generalize, you can make it a template too and also acceptbasic_streaminstead of plainstring. It has different behaviors to standard manipulators in some cases. Because it works by returning the proxy object, it will not work for cases like