问题描述
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++ 宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)