类的自定义流操纵器

Pat*_*ick 0 c++ stream manipulators

我正在尝试编写一个简单的审计类,它通过运算符 << 获取输入,并在接收到这样的自定义操纵器后编写审计:

class CAudit
{
public:
    //needs to be templated
    CAudit& operator << ( LPCSTR data ) {
        audittext << data;
        return *this;
    }

    //attempted manipulator
    static CAudit& write(CAudit& audit) { 
        //write contents of audittext to audit and clear it
        return audit; 
    }

private:
    std::stringstream audittext;
};

//to be used like
CAudit audit;
audit << "Data " << data << " received at " << time << CAudit::write;
Run Code Online (Sandbox Code Playgroud)

我认识到代码中的重载运算符不返回流对象,但想知道是否仍然可以使用类似语法的操纵器。目前,编译器将 '<<' 视为二元右移运算符。

感谢您的任何意见,帕特里克

rob*_*.14 5

为了使其工作,您必须为函数添加运算符 << 的重载,而不是从中调用函数:

 class CAudit
 {
  //...other details here as in original question

  CAudit& operator << (CAudit & (*func)(CAudit &))
  {
        return func(*this);
  }
 };

 CAudit audit;
 audit << "some text" << CAudit::write;
Run Code Online (Sandbox Code Playgroud)