gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:40:05 28 4
gpt4 key购买 nike

所以我用这样的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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com