开发者

Creating ostream manipulators for a specific class

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.


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜