C++中的多语句宏

Jes*_*ien 4 c++ macros

在C++中,是否可以使用嵌套的if语句创建一个多语句宏,如下所示?我已经尝试了一段时间了,我得到了第二个if语句无法看到' 符号 ' 的范围问题.也许我需要进一步了解宏.

#define MATCH_SYMBOL( symbol, token)
     if(something == symbol){
          if( symbol == '-'){
          }else if (symbol != '-'){
          }
     other steps;
     }
Run Code Online (Sandbox Code Playgroud)

Amb*_*ber 11

对于多行宏,您需要在\除最后一行之外的所有行的末尾添加一个字符,以告诉宏处理器继续解析下一行的宏,如下所示:

#define MATCH_SYMBOL( symbol, token) \
     if(something == symbol){        \
          if( symbol == '-'){        \
          }else if (symbol != '-'){  \
          }                          \
     other steps;                    \
     }
Run Code Online (Sandbox Code Playgroud)

现在,它试图将其解释为1行宏,然后将一些实际代码解释为文件顶部,这不是您想要的:

#define MATCH_SYMBOL( symbol, token)

// and then... wrongly thinking this is separate...

 if(something == symbol){ // symbol was never defined, because the macro was never used here!
      if( symbol == '-'){
      }else if (symbol != '-'){
      }
 other steps;
 }
Run Code Online (Sandbox Code Playgroud)

  • 或者使用着名的`do {} while(0)`技巧. (7认同)
  • 并且要小心这样做,因为用户并不明白这个宏包含if语句.一个典型的问题是当你在一系列没有括号的嵌套`if`-`else`语句中使用这样的语句时. (2认同)

Tim*_*ter 8

如果您使用的是C++,则应该完全避免使用宏.它们不是类型安全的,它们不是名称空间感知的,它们很难调试,只是它们非常混乱.

如果您需要与类型无关的功能,请使用模板:

template <typename T>
bool match_symbol(T symbol, T token) {
    if(something == symbol){
        if( symbol == '-'){
        }else if (symbol != '-'){
        }
    ...
Run Code Online (Sandbox Code Playgroud)

或者如果参数可以是不同的类型:

template <typename T, typename V>
bool match_symbol(T symbol, V token) {
    if(something == symbol){
        if( symbol == '-'){
        }else if (symbol != '-'){
        }
    ...
Run Code Online (Sandbox Code Playgroud)

  • @LiraNuna如果它在头文件中你应该包含`inline`,否则它只是建议编译器它可以自由忽略.是否内联与我的观点无关. (5认同)