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

Is there anyway to write the following as a C++ macro?(无论如何将以下内容编写为 C++ 宏?)
本文介绍了无论如何将以下内容编写为 C++ 宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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.

这篇关于无论如何将以下内容编写为 C++ 宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Prevent class inheritance in C++(防止 C++ 中的类继承)
Why should I declare a virtual destructor for an abstract class in C++?(为什么要在 C++ 中为抽象类声明虚拟析构函数?)
Why is Default constructor called in virtual inheritance?(为什么在虚拟继承中调用默认构造函数?)
C++ cast to derived class(C++ 转换为派生类)
C++ virtual function return type(C++虚函数返回类型)
Is there any real risk to deriving from the C++ STL containers?(从 C++ STL 容器派生是否有任何真正的风险?)