PRODUCT : Borland C++ NUMBER : 1543 VERSION : All OS : All DATE : October 25, 1993 PAGE : 1/2 TITLE : Class manipulator example // Making your own manipulator with your own class #include #include class m_stream: public ostrstream { public: char buffer[458]; m_stream() : ostrstream(buffer, sizeof(buffer)) {} friend m_stream& output(m_stream&); friend m_stream& operator << ( m_stream&, const char *); friend m_stream& operator << ( m_stream& m, m_stream& (*f)(m_stream&) ); }; // We need to re-do all of ostream so that the operators will // return m_stream references rather than ostream &'s // Our m_stream operators simply call the base class operators // The m_stream operators can be modified to add extended // functionality inline m_stream& ends(m_stream& m) { (ostream &) m << ends; return m; } inline m_stream& operator << ( m_stream & m, const char * k) { (ostream &) m << k; return m; } // Now we can use our own operator << ( taking function pointer) // to use a manipulator specialized for m_stream operations. // This avoids any casts from ostream& to m_stream&, which // would be dangerous. (casting m_stream& to ostream& won't // hurt.) m_stream& operator << ( m_stream& m, m_stream& (*f)(m_stream&) ) { PRODUCT : Borland C++ NUMBER : 1543 VERSION : All OS : All DATE : October 25, 1993 PAGE : 2/2 TITLE : Class manipulator example return f(m); } // And here is the manipulator in question, which ends up // being called by the function above through a function // pointer when we use it. m_stream& output(m_stream& m) { // do the appropriate output operation here. // m.str() returns m's string cout << m.str(); m.seekp(0); // "flush" by rewinding to 0 return m; } int main() { m_stream mout; mout << "This is the test.\n" << ends << output; mout << "Test Line 2.\n" << ends << output; return 0; } DISCLAIMER: You have the right to use this technical information subject to the terms of the No-Nonsense License Statement that you received with the Borland product to which this information pertains.