How to store formatting settings with an IOStream?

Viewed 471

When creating formatted output for a user defined type it is often desirable to define custom formatting flags. For example, it would be nice if a custom string class could optionally add quotes around the string:

String str("example");
std::cout << str << ' ' << squotes << str << << ' ' << dquotes << str << '\n';

should produce

example 'example' "example"

It is easy enough to create manipulators for changing the formatting flags themselves:

std::ostream& squotes(std::ostream& out) {
    // what magic goes here?
    return out;
}
std::ostream& dquotes(std::ostream& out) {
    // similar magic as above
    return out;
}
std::ostream& operator<< (std::ostream& out, String const& str) {
    char quote = ????;
    return quote? out << quote << str.c_str() << quote: str.c_str();
}

... but how can the manipulators store which quotes should be used with the stream and later have the output operator retrieve the value?

1 Answers
Related