我想写一个像这样的功能:
DEBUG_LOG<<"append" << 123 <<" float=" <<123.432 << std::endl;
<<
这个运算符看起来像:
Logger& operator<<(const T& message)
{
if(message == std::endl)
{
flushBuffer();
return *this;
}
std::stringstream ss;
ss << message;
writeToBuffer(ss.str());
return *this;
}
现在,这肯定不能编译,因为 if 语句有编译错误。
flushBuffer()
将一行写入文件并清除缓冲区,writeToBuffer()
附加到缓冲区。你能建议一些东西来代替 if 语句吗?基本上我需要知道何时收到换行符,相应地会调用其他两个函数。
最佳答案
我不确定写入缓冲区或刷新缓冲区的内容是什么,我在后台使用了 std::stringstream。
std::endl 不是您的模板函数的有效类型,它将无法编译(错误消息如下:未定义对 `operator<<(logger&, std::ostream& (*)(std::ostream&) )',因此您需要为其提供匹配项并在其中实现所需的行为。
#include <iostream>
#include <sstream>
#include <string>
class logger
{
std::stringstream buffer;
template<typename T> friend logger& operator<<(logger& log, const T& t);
friend logger& operator<<(logger& log, std::ostream& (*var)(std::ostream&));
public:
void flush()
{
std::cout << buffer.str();
}
};
template<class T>
logger& operator<<(logger& log, const T& t)
{
log.buffer << t;
return log;
}
logger& operator<<(logger& log, std::ostream& (*var)(std::ostream&)) {
log.buffer << std::endl;
return log;
}
int main()
{
logger l;
l << "append " << 123 <<" float=" << 123.432 << std::endl;
l << "some other stuff here" << std::endl;
l.flush();
}
如果这不仅仅是练习,我建议您在从头开始做某事之前从众多可用的库中选择一个。
关于c++ - 想要检查模板参数是否为 std::endl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66292717/