C++ uses the indeterminate parameter macro to calculate the number of indeterminate parameters

C++ macro functions support indeterminate parameters, so how to determine the number of indeterminate parameters?

Cut the nonsense and go straight to the code.

#define DBG_16TH(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, \
                      _14, _15, _16, ...)                                     \
  _16
#define DBG_NARG(...) \
  DBG_16TH(__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)

The above piece of code can use the variable parameter macro function to calculate the number of input parameters.

#include <iostream>
using namespace std;

#define DBG_16TH(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, \
                      _14, _15, _16, ...)                                     \
  _16
#define DBG_NARG(...) \
  DBG_16TH(__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
int main() {
    cout << DBG_NARG(arg1, arg2, arg3) << endl;
    cout << DBG_NARG(arg1, arg2, arg3,arg4) << endl;
    return 0;
}

The output of the above program is:

3
4

Explain that the variable parameter macro function DBG_NARG(...) can automatically calculate the number of parameters according to the parameters passed in.

Principle analysis:

When passing parameters to the indeterminate macro function DBG_NARG(...), the parameters will be passed to DBG_16TH():

// DBG_NARG传入1个参数
DBG_16TH(arg1, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, \
    1, 0)   // 第16个参数为1

// DBG_NARG传入2个参数
DBG_16TH(arg1, arg2,15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, \
    2, 1, 0) // 第16个参数为2

// DBG_NARG传入3个参数
DBG_16TH(arg1, arg2, agr3, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, \
    4, 3, 2, 1, 0)  // 第16个参数为3
而DBG_16TH也是一个不定参数宏函数,并且将参数截断为第16个参数,当参数通过DBG_NARG传递
给DBG_16TH是,将15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0往后推:
传入1个参数时:DBG_16TH第16个参数为1,即获得参数个数为1
传入2个参数时:DBG_16TH第16个参数为2,即获得参数个数为2
传入3个参数时:DBG_16TH第16个参数为3,即获得参数个数为3
...

Guess you like

Origin blog.csdn.net/weixin_43354152/article/details/129773232