Creating ostream manipulators for a specific class

Posted by petersohn on Stack Overflow See other posts from Stack Overflow or by petersohn
Published on 2010-04-22T09:27:48Z Indexed on 2010/04/22 9:33 UTC
Read the original article Hit count: 235

Filed under:
|
|

I have a class that is derived from ostream:

class my_ostream: public std::ostream
{
    // ...
}

I want to make a manipulator (for example do_something), that works specifically to this class, like this:

my_ostream s;
s << "some text" << do_something << "some more text";

I did the following:

std::ostream &do_something(std::ostream &os)
{
    my_ostream *s = dynamic_cast<my_ostream*>(&os);
    if (s != NULL)
    {
        // do something
    }
    return os;
}

This works, but is rather ugly. I tried the following:

my_ostream &do_something(my_ostream &s)
{
    // do something
    return s;
}

This doesn't work. I also tried another approach:

class my_ostream: public std::ostream
{
   // ...
   my_ostream &operator<<(const do_something & x)
   {
       // do something
       return *this;
   }
}

This still doesn't work.

© Stack Overflow or respective owner

Related posts about c++

Related posts about iostream