Listing 3
#include "streamstate.h"
#include <iostream>
#include <ostream>
using namespace std;
// the "state" object
struct bracketing
{
bracketing(char l = '(', char r = ')')
: left_(l), right_(r) {}
char left_, right_;
};
// the hypothetical complex class
class mycomplex
{
public:
ostream& print(ostream &os) const
{
// get the stream state from the
// slot dedicated to "bracketing"
bracketing &b = streamstate<bracketing>::get(os);
return os << b.left_ << re_ << ", " << im_ << b.right_;
}
// other operations and members as in Listing 1.
};
// inserter for mycomplex and setbrackets as in Listing 1.
// ...
ostream & operator<<(ostream &os, bracketing b)
{
// set the stream state in the private slot
streamstate<bracketing>::get(os) = b;
return os;
}
int main() { /* ... */ }