无论如何将以下内容编写为 C++ 宏?

2021-12-19 00:00:00 logging thread-safety c++ ostringstream
my_macro << 1 << "hello world" << blah->getValue() << std::endl;

应该扩展为:

std::ostringstream oss;
oss << 1 << "hello world" << blah->getValue() << std::endl;
ThreadSafeLogging(oss.str());

推荐答案

#define my_macro my_stream()
class my_stream: public std::ostringstream  {
public:
    my_stream() {}
    ~my_stream() {
        ThreadSafeLogging(this->str());
    }
};
int main() {
    my_macro << 1 << "hello world" << std::endl;
}

创建了一个 my_stream 类型的临时文件,它是 ostringstream 的子类.对该临时文件的所有操作都像在 ostringstream 上一样工作.

A temporary of type my_stream is created, which is a subclass of ostringstream. All operations to that temporary work as they would on an ostringstream.

当语句结束时(即在 main() 中整个打印操作的分号之后),临时对象超出范围并被销毁.my_stream 析构函数使用先前收集"的数据调用 ThreadSafeLogging.

When the statement ends (ie. right after the semicolon on the whole printing operation in main()), the temporary object goes out of scope and is destroyed. The my_stream destructor calls ThreadSafeLogging with the data "collected" previously.

已测试 (g++).

感谢/感谢 dingo 指出如何简化整个事情,所以我不需要重载的 operator<<.太糟糕了,无法分享点赞.

Thanks/credits to dingo for pointing out how to simplify the whole thing, so I don't need the overloaded operator<<. Too bad upvotes can't be shared.

相关文章