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++ 宏?


- 从python回调到c++的选项 2022-11-16
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 近似搜索的工作原理 2021-01-01
- C++ 协变模板 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07