0

我正在尝试使用定义宏来实现我的记录器的逻辑系统,当定义某些切换时,它将扩展为空。问题是,当我堆叠多个这些开关时,一个嵌套在另一个内部(例如调用 IF_SWITCH_1 类似函数的宏),我得到了代码块中列出的多个错误。 是什么导致了这些错误?我该如何修复它们?

    //Creation of the switches
    #define _ADD_PARTS2(part1, part2, ...) part1 ## part2 (__VA_ARGS__)
    #define _ADD_PARTS(part1, part2, ...) _ADD_PARTS2(part1, part2, __VA_ARGS__)
    #define _LOGIC_SWITCH_(name, cond, ...) _ADD_PARTS(name, cond, __VA_ARGS__)
    
    //Toggles
    #define CONDITION_1 true
    #define CONDITION_2 true
    
    //Switches
    #define IF_SWITCH_2_true(a, b, c) std::cout << "Passed" << std::endl
    #define IF_SWITCH_2_false(...)
    
    #define IF_SWITCH_2(a, b, c) _LOGIC_SWITCH_(IF_SWITCH_2_, CONDITION_1, a, b, c)
    
    #define IF_SWITCH_1_true(a, b, c) IF_SWITCH_2(a, b, c)
    #define IF_SWITCH_1_false(...)
    
    #define IF_SWITCH_1(a, b, c) _LOGIC_SWITCH_(IF_SWITCH_1_, CONDITION_1, a, b, c)
    
    //Use
    IF_SWITCH_2(1, 1, 1); //Compiles and passes
    IF_SWITCH_1(1, 1, 1); //"IF_SWITCH_2" was not declared in this scope; 
    //_LOGIC_SWITCH_ was not declared in this scope; 
    //Use of undeclared indentifier IF_SWITCH_2_
    
    //Switching on and off
    #undef CONDITION_2 
    #define CONDITION_2 false //Any invocation from this point on wont pass past the logic switch
    IF_SWITCH_2(1, 1, 1); //Wont pass

据我所知,更改定义的顺序对错误没有影响。

使用 MinGW 8.10 64 位编译

4

1 回答 1

0

是什么导致了这些错误?

扩展运行一次。一旦一个宏被展开,它就不会再次被展开,在嵌套的宏调用中也是如此。无论如何,链条是:

IF_SWITCH_1(1, 1, 1)
_LOGIC_SWITCH_(IF_SWITCH_1_, CONDITION_1, 1, 1, 1)  // step 2
_ADD_PARTS(IF_SWITCH_1_, true, 1, 1, 1)
_ADD_PARTS2(IF_SWITCH_1_, true, 1, 1, 1)
IF_SWITCH_1_true(1, 1, 1)
IF_SWITCH_2(1, 1, 1)
_LOGIC_SWITCH_(IF_SWITCH_2_, CONDITION_1, 1, 1, 1)  
// _LOGIC_SWITCH_ was expanded at step #2
_LOGIC_SWITCH_(IF_SWITCH_2_, true, 1, 1, 1)  
// expanding stops here

我该如何修复它们?

首先,带有前导下划线后跟大写字母的标识符保留用于实现。不要在您自己的代码中使用此类标识符。

如果您希望进行运行时评估,我建议:

static inline void if_switch_2_execute(int a, int b, int c) {
    std::cout << "passed" << std::endl;
}
#define IF_SWITCH_2(a, b, c)  (CONDITION_2?if_switch_2_execute(a, b, c):(void)0)
#define IF_SWITCH_1(a, b, c)  (CONDITION_1?IF_SWITCH_2(a, b, c):(void)0)

无论如何,解决方法是将评估_LOGIC_SWITCH_从嵌套调用_LOGIC_SWITCH_移到上层,以便_LOGIC_SWITCH_在一个评估链中仅扩展一次(我不知道如何解释,这就是我的理解......:/) . 这就是为什么这样做很典型#define MACRO(something) CHOOSE_FUNCTION_TO_CALL(__VA_ARGS__)(__VA_ARGS__)

#define CONDITION_1 true
#define CONDITION_2 true

#define CONCAT(a, b) a##b
#define XCONCAT(a, b) CONCAT(a, b)   // this is your _LOGIC_SWITCH_

#define IF_SWITCH_2_true(a, b, c)  std::cout << "Passed" << std::endl
#define IF_SWITCH_2_false(...)
#define IF_SWITCH_2(a, b, c) XCONCAT(IF_SWITCH_2_, CONDITION_2)(a, b, c)

#define IF_SWITCH_1_true(a, b, c) IF_SWITCH_2(a, b, c)
#define IF_SWITCH_1_false(...)
#define IF_SWITCH_1(a, b, c)  XCONCAT(IF_SWITCH_1_, CONDITION_1)(a, b, c)
于 2020-08-13T21:36:03.047 回答