类的自定义流操纵器 [英] custom stream manipulator for class

查看:201
本文介绍了类的自定义流操纵器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个简单的审计类,通过operator<<并在收到如下所示的自定义操作符后写入审计:

I am trying to write a simple audit class that takes input via operator << and writes the audit after receiving a custom manipulator like this:

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;

我知道我的代码中的重载运算符不返回一个流对象,仍然可以使用像操纵器的语法。现在编译器看到'<<'作为二进制右移位运算符。

I recognise that the overloaded operator in my code does not return a stream object but was wondering if it was still possible to use a manipulator like syntax. Currently the compiler is seeing the '<<' as the binary right shift operator.

感谢任何输入,
Patrick

Thanks for any input, Patrick

推荐答案

为了使它工作,你必须添加operator<<对于函数,
比调用函数:

To make it work you have to add overload of operator << for functions, than call the function from it:

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

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

 CAudit audit;
 audit << "some text" << CAudit::write;

这篇关于类的自定义流操纵器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆