如何像 std C++ 流一样使用我的日志记录类?

2024-08-13C/C++开发问题
1

本文介绍了如何像 std C++ 流一样使用我的日志记录类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个工作记录器类,它将一些文本输出到富文本框(Win32,C++)中.问题是,我总是这样使用它:

I've a working logger class, which outputs some text into a richtextbox (Win32, C++). Problem is, i always end up using it like this:

stringstream ss;  
ss << someInt << someString;  
debugLogger.log(ss.str());

相反,像使用流一样使用它会方便得多:

instead, it would be much more convenient to use it like a stream as in:

debugLogger << someInt << someString;

有没有比将所有内容转发到内部字符串流实例更好的方法?如果这样做,我什么时候需要冲洗?

Is there a better way than forwarding everything to an internal stringstream instance? If'd do this, when would i need to flush?

推荐答案

您需要为您的班级适当地实施 operator <<.一般模式如下所示:

You need to implement operator << appropriately for your class. The general pattern looks like this:

template <typename T>
logger& operator <<(logger& log, T const& value) {
    log.your_stringstream << value;
    return log;
}

请注意,这会处理(非const)引用,因为该操作会修改您的记录器.另请注意,您需要返回 log 参数才能使链接正常工作:

Notice that this deals with (non-const) references since the operation modifies your logger. Also notice that you need to return the log parameter in order for chaining to work:

log << 1 << 2 << endl;
// is the same as:
((log << 1) << 2) << endl;

如果最里面的操作没有返回当前的 log 实例,所有其他操作要么在编译时失败(错误的方法签名)要么在运行时被吞没.

If the innermost operation didn't return the current log instance, all other operations would either fail at compile-time (wrong method signature) or would be swallowed at run-time.

这篇关于如何像 std C++ 流一样使用我的日志记录类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6