views:

97

answers:

1

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.

+1  A: 

You need to add support for manipulators in your class:

#include<iostream>
class my_ostream : public std::ostream
{
    public:
    std::string prefix;

    my_ostream():prefix("*"){}

    // manipulator support here:
    my_ostream& operator<<( my_ostream&(*f)(my_ostream&)){
        f(*this);
        return *this;
    }
};

my_ostream& operator<<(my_ostream &st, const std::string &s){
      std::cout << st.prefix << s;
      return st;
}

// manipulator: clear prefix
my_ostream& noprefix(my_ostream &st){
   st.prefix="";
}

int main(){
  my_ostream s;
  std::string str1("text");
  std::string str2("text");
  s << str1 << noprefix << str2;
}
catwalk
I tried it, and it doesn't work. It compiles, but the manipulator function is not called. I find this really strange, because it is exactly how it is done in `std::ostream`.
petersohn
@petersohn: it must be a problem with your compiler, because the above code works for me as it is (g++ 3.4.4)
catwalk