Is there anyway to write the following as a C++ macro?(无论如何将以下内容编写为 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++ 宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无论如何将以下内容编写为 C++ 宏?
基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
