如何使用继续或中断表达式编写多行宏

How to write multiline macro with continue or break expression

本文关键字:表达式 何使用 继续 中断      更新时间:2023-10-16

在我们最近的项目中,我编写了一个宏,该宏将在给定条件下继续,并且如此处所述 C 多行宏:do/while(0( vs 作用域块 我试图使用 do--while 来实现这一点。下面是示例代码来说明这一点:

#define PRINT_ERROR_AND_CONTINUE_IF_EMPTY(dummy,dummystream,symbol,errorString) 
  do{ 
    if(dummy.empty())
    {
        dummyStream<<symbol<<",Failed,"<<errorString<<std::endl;
        continue;
    }
  }while(0) 
int main()
{
  int x =9;    
  std::ofstream& ofsReportFile;
  while(x>5)
  {
      std::string str;
      PRINT_ERROR_AND_CONTINUE_IF_EMPTY(str,ofsReportFile,"Test","Test String is Empty");
      std::cout<<x<<std::endl;
      x--;
  }
  return 0;
}

但是,这并没有按预期工作,原因可能是在里面继续语句,所以质疑如何使用 continue 语句编写多行宏,并且该宏的用户可以像 CONTINUE_IF_EMPTY(str(;

lambda怎么样?这看起来像是该宏的一个很好的替代品,该宏既是全局的(就像所有宏一样(,又是奇怪的特定。此外,您还可以获得捕获以帮助减少重复的参数。

int main()
{
    int x = 9;
    std::ofstream& ofsReportFile = /* ... */;
    auto const reportEmpty = [&](std::string const &str) {
        if(str.empty()) {
            ofsReportFile << "Test, Failed, Test String is Empty" << std::endl;
            return true;
        }
        return false;
    };
    while(x > 5)
    {
        std::string str;
        if(reportEmpty(str))
            continue;
        std::cout << x << std::endl;
        x--;
    }
}
相关文章: