2

我有一个从 ostream 派生的类:

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

我想制作一个专门针对此类的操纵器(例如do_something),如下所示:

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

我做了以下事情:

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

这有效,但相当难看。我尝试了以下方法:

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

这行不通。我还尝试了另一种方法:

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

这仍然行不通。

4

1 回答 1

3

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;
}
于 2010-04-22T09:52:00.857 回答