具有延迟函数调用的 while 循环宏

Macro for while loop with deferred function call

我想构建一个宏,其中每次循环结束迭代时都会调用预定义函数(此处由 "call fcn here" 模拟)。这是我到目前为止所拥有的,它确实有效。

有没有更短的方法,最终用更多的宏魔法来编写这样的行为?

#define MYWHILE(condition) \
        while(  \
          []()->bool {  \
          static bool called = false; \
          if(called) std::cout<<"call fcn here"<<std::endl; \
          called=true; return true;}() \
          && condition)

这个宏应该在代码中的几个地方使用,以确保没有人在编写繁忙的等待循环时忘记调用该函数。

一个典型的例子是:

while(true){

 bool b = foo();
 if(b){
   break;
 }

 ros::spinOnce(); 
}

在哪里经常忘记调用 ros::spinOnce(),所以我只是将示例代码替换为:

MYWHILE(true){

  bool b = foo();
  if(b){
    break;
  }
}

纯 C - 代码也可以。

I would like to construct a macro where a predefined function (here simulated by "call fcn here") is called every time when the loop ends an iteration, but NOT at the first time.

由于你提供的代码和你的问题有冲突,所以不清楚你想要什么行为。要实现上述内容,我建议您根本不要使用宏,只需将您的代码编写为:

do {
  if(!condition)
    break;

  // More code here

} while(fcn());

您可以将需要的内容打包到 for 循环中,而不是看起来很复杂的 while 循环:

for (; condition; fcn())

将在每次迭代结束时调用该函数,然后再重新评估条件。

刚刚有什么问题:

while(!foo()) {
    ros::spinOnce();
}

这在逻辑上等同于:

while(true){
    bool b = foo();

    if(b){
        break;
    }
    ros::spinOnce(); 
}

但比:

简单得多
MYWHILE(true){
    bool b = foo();

    if(b){
        break;
    }
}