在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)
如果您使用的是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)