Overloading Macro on Number of Arguments

后端 未结 8 1647
离开以前
离开以前 2020-11-22 04:25

I have two macros FOO2 and FOO3:

#define FOO2(x,y) ...
#define FOO3(x,y,z) ...

I want to define a new macro

8条回答
  •  一生所求
    2020-11-22 05:08

    Here is a more compact version of the answer above. With example.

    #include 
    using namespace std;
    
    #define OVERLOADED_MACRO(M, ...) _OVR(M, _COUNT_ARGS(__VA_ARGS__)) (__VA_ARGS__)
    #define _OVR(macroName, number_of_args)   _OVR_EXPAND(macroName, number_of_args)
    #define _OVR_EXPAND(macroName, number_of_args)    macroName##number_of_args
    
    #define _COUNT_ARGS(...)  _ARG_PATTERN_MATCH(__VA_ARGS__, 9,8,7,6,5,4,3,2,1)
    #define _ARG_PATTERN_MATCH(_1,_2,_3,_4,_5,_6,_7,_8,_9, N, ...)   N
    
    
    //Example:
    #define ff(...)     OVERLOADED_MACRO(ff, __VA_ARGS__)
    #define ii(...)     OVERLOADED_MACRO(ii, __VA_ARGS__)
    
    #define ff3(c, a, b) for (int c = int(a); c < int(b); ++c)
    #define ff2(c, b)   ff3(c, 0, b)
    
    #define ii2(a, b)   ff3(i, a, b)
    #define ii1(n)      ii2(0, n)
    
    
    int main() {
        ff (counter, 3, 5)
            cout << "counter = " << counter << endl;
        ff (abc, 4)
            cout << "abc = " << abc << endl;
        ii (3)
            cout << "i = " << i << endl;
        ii (100, 103)
            cout << "i = " << i << endl;
    
    
        return 0;
    }
    

    Run:

    User@Table 13:06:16 /c/T
    $ g++ test_overloaded_macros.cpp 
    
    User@Table 13:16:26 /c/T
    $ ./a.exe
    counter = 3
    counter = 4
    abc = 0
    abc = 1
    abc = 2
    abc = 3
    i = 0
    i = 1
    i = 2
    i = 100
    i = 101
    i = 102
    

    Note that having both _OVR and _OVR_EXPAND may look redundant, but it's necessary for the preprocessor to expand the _COUNT_ARGS(__VA_ARGS__) part, which otherwise is treated as a string.

提交回复
热议问题