有没有写下面的一个C ++宏? [英] Is there anyway to write the following as a C++ macro?

查看:151
本文介绍了有没有写下面的一个C ++宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

my_macro << 1 << "hello world" << blah->getValue() << std::endl;

应扩展为:

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

谢谢!

答案是真棒。我们可以再增加8次并赢得这个回应者的徽章吗?

the accepted answer is awesome. Can we upvote 8 more times and win this responder a badge?

(回答只需要6个以上的积分)。

(The answer only needs 6 more upvotes).

另外4张票,从21位到25位。

4 more votes to go from 21 to 25.

3位。 : - )

胜利。 : - )

推荐答案

#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 - Stack Overflow> dingo 来指出如何简化整个事情,所以我不需要重载的运算符<< 。无法分享太糟糕的upvote。

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆