首页 > 解决方案 > 在没有局部变量访问的情况下继续在 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,但我完全不知道如何。请帮助,最短的答案获胜!

标签: c++11for-looplogginglambda

解决方案


问:有没有一种方法可以使用宏来粘贴所有位置(无需再次调用 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 中,您必须将它们替换为正确的类型。


推荐阅读