c++11 - 在没有局部变量访问的情况下继续在 for 循环中附加 [to stream]
问题描述
想象一下,您有以下代码,其中logDebug()
昂贵或不适合多次调用:
QDebug d = logDebug();
d << __FUNCTION__ << ":";
d << "positions separated with \" --- \":";
for (const auto& str : positions)
{
d << "---" << str;
}
已经存在一个宏(只是为了正确替换函数名),它替换了前 2 行:
#define LOG_FUNCTION this->logDebug() << __FUNCTION__ << ":"
它通过调用创建局部变量logDebug()
。一旦调用,您只能使用operator<<
到宏。问题是您不能将 for 循环主体附加到记录器。
问:有没有办法可以使用宏粘贴所有位置(无需logDebug
再次调用?我想这应该可以使用 lambdas,但我完全不知道如何。请帮助,最短的答案获胜!
解决方案
问:有没有一种方法可以使用宏来粘贴所有位置(无需再次调用 logDebug?我想这应该可以使用 lambdas,但我不知道该怎么做。
我想可以使用以下方法(使用std::cout
而不是logDebug()
)
#include <iostream>
#define LOG_FUNCTION std::cout << __FUNCTION__ << ": "
#define LOG_DEB(ps) \
[](auto & s, auto const & _ps) { for ( auto const & p : _ps ) s << p; } \
(LOG_FUNCTION, ps)
int main ()
{
int a[] { 0, 1, 2, 3, 4 };
LOG_DEB(a);
}
我使用了几个auto
作为 lambda 参数的类型,这仅从 C++14 开始有效。
在 C++11 中,您必须将它们替换为正确的类型。
推荐阅读
- python - 调查内容的持续时间
- dns - DNS LoadBalancer RoundRobbin 是否可以进行优雅降级?
- latex - 乳胶使用不同的背景颜色突出 \citation 和 \ref
- angular - 如何处理 Angular i18n 翻译中的重复文本
- excel - VBA Little Hashmap 获取路径问题
- java - 如何在不安装 Hadoop 和设置 dll 库的情况下将数据加载到 s3
- c# - 如何发布 OData 实体并将其同时链接到多个现有实体?
- python - 如何在 Windows 上同时运行两个 Python 脚本
- firebase - 实时数据库中根节点和命名空间节点之间最好的是什么?
- apache-spark - 使用 2.8.0 hadoop aws jar 时无法使用 spark 从 s3 读取,使用 hadoop aws 2.7.3 时无法将增量表写入 s3