自定义流到C++中的方法?

Joo*_*kia 3 c++ stream

我正在制作一个记录器,我希望有一些像流一样的事情发生,理想情况下,CLogger << "Testing, " << 1 << ",2,3\n";而不是CLogger->log("Testing, %i,2,3", 1);

我的问题是我该怎么做?我不想直接创建一个到stdout的流,因为我想使用我自己的方法,包括编写文件等.我已经考虑使用某个结构重载,该结构将当前流缓冲区刷新为方法,但我必须这样做CLogger << flush << "Test!\n";,这有点奇怪.

有人知道怎么做这个吗?

Rob*_*obᵩ 13

如果您需要的只是将某些日志消息指向文件,您是否考虑过std::ofstream

否则,我喜欢从中派生我的日志类std::ostream,所以我得到了所有的流优点.诀窍是将所有特定于应用程序的代码放在关联的streambuf类中.考虑:

#include <iostream>
#include <sstream>

class CLogger : public std::ostream {
private:
    class CLogBuf : public std::stringbuf {
    private:
        // or whatever you need for your application
        std::string m_marker;
    public:
        CLogBuf(const std::string& marker) : m_marker(marker) { }
        ~CLogBuf() {  pubsync(); }
        int sync() {
            std::cout << m_marker << ": " << str();
            str("");
            return std::cout?0:-1;
        }

    };

public:
    // Other constructors could specify filename, etc
    // just remember to pass whatever you need to CLogBuf
    CLogger(const std::string& marker) : std::ostream(new CLogBuf(marker)) {}
    ~CLogger() { delete rdbuf(); }
};

int main()
{
    CLogger hi("hello");
    CLogger bye("goodbye");

    hi << "hello, world" << std::endl;
    hi << "Oops, forgot to flush.\n";
    bye << "goodbye, cruel world\n" << std::flush;
    bye << "Cough, cough.\n";
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • CLogger构造函数可以使用您需要使用的任何参数 - 文件名,输出语言,指向底层日志数据的指针等等.只需将数据传递到CLogBuf类.
  • 在响应std :: flush期间,会自动调用CLogBuf的sync().


Moo*_*ice 6

退房operator <<,这是STL的流超载.

class CLogger
{
public:
    CLogger& operator << (const std::string& _rhs)
    {
        // work with it here
        return *this;
    }; // eo operator <<
}; // eo class CLogger
Run Code Online (Sandbox Code Playgroud)

编辑:

请参阅此页面,其中概述了std :: ostream如何operator <<为不同类型重载:

http://www.cplusplus.com/reference/iostream/ostream/operator%3C%3C/