c++ - 日志记录,如何获得命令结束?

标签 c++ templates logging stl std

所以我用这样的Log class :

#include <stdio.h>
#include <iostream>

class Log
{
public:
    int i;
    Log()
    {
        i = 0;
    }

    template <class T>
    Log &operator<<(const T &v)
    {
        i++;
        std::cout << i << ":"  << v << ";" <<std::endl;
        return *this;
    }
    Log &operator<<(std::ostream&(*f)(std::ostream&)) 
    {
        i++;
        std::cout << i << ":"  << *f << ";" <<std::endl;
        return *this;
    }

    ~Log()
    {
        std::cout << " [end of message]" << std::endl;
    }
};

我这样使用:

#include <log.h>

int main()
{
    Log a;
    a << "here's a message" << std::endl;
    a << "here's one with a number: " << 5;
    std::cin.get();
}

我希望我的日志类在我输入“;”时得到意思是如果我有 a << "here's a message" << std::endl;我希望它能够得到它是 oue 日志消息和 a << "here's one with a number: " << 5;是另一个。

最近它输出下一条消息:

1:here's a message;
2:
;
3:here's one with a number: ;
4:5;

我想保留它的语法(无限数量的 << ,大范围的值类型,在 api 中没有 () )但让它输出:

1:here's a message
;
2:here's one with a number: 5;

如何做这样的事情?

最佳答案

制作operator<<返回一个临时值,它将放置 endl销毁并转发所有operator<<调用主要对象。这样,endl保证只调用一次。

class Log
{
struct EndlOnDeath {
    Log* log;
    EndlOnDeath(Log* ptr)
        : log(ptr) {}
    template<typename T> EndlOnDeath& operator<<(const T& val) {
        (*log) << val;
    }
    ~EndlOnDeath() {
        (*log) << std::endl;
    }
};

public:
    int i;
    Log()
    {
        i = 0;
    }

    template <class T>
    EndlOnDeath operator<<(const T &v)
    {
        i++;
        std::cout << i << ":"  << v << ";";
        return this;
    }
    Log &operator<<(std::ostream&(*f)(std::ostream&)) 
    {
        i++;
        std::cout << i << ":"  << *f << ";" <<std::endl;
        return *this;
    }

    ~Log()
    {
        std::cout << " [end of message]" << std::endl;
    }
};

关于c++ - 日志记录,如何获得命令结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7099769/

相关文章:

c++ - 从另一个参数引用的模板可变参数

javascript - 下划线如何替换变量?

c# - 在运行 Asp.Net Core 2 的 Webapi 2 上使用 Serilog 的 DI ILogger

c++ - OpenGL 帧缓冲区非常慢

c++ - 从代码添加时qt按钮无法点击

c++ - 调用构造函数时程序停止运行,c++

c++ - 模板而不是 cpp 预处理器以避免链接?

azure - 从另一个订阅的 OMS 中查看来自 Azure Service Fabric 的日志

bash - 在 Bash 脚本中使用日志记录

C++ 从远程控制台应用程序检索内容