如何使用continue或break表达式编写多行宏

时间:2017-03-29 11:25:40

标签: c++ macros

在我们最近的项目中,我编写了一个宏,它将在给定条件下继续,并在此处解释C multi-line macro: do/while(0) vs scope block我尝试使用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)那样调用它;

1 个答案:

答案 0 :(得分:1)

一个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--;
    }
}