c++ variadic macro: how to retrieve arguments values

Viewed 118

In the class there are a lot of methods with similar implementation, only method's name and argument-list different:

void function1 (int a, bool b)
{
    mMember->function1(a, b);
}

void function2 (double a, string b)
{
    mMember->function2(a, b);
}

It is required to replace all them with variadic macro. Something like this

#define MYMACRO(funcname, ...)  void funcname (__VA_ARGS__)  { mMember->funcname (__VA_ARGS__)}

but it is generated into such call

mMember->function1(int a, bool b)

And of course gives compilation errors.

How can parameters' values be got inside macro, so that to pass them into mMember->funcname without types?

mMember->function1(a, b)
1 Answers

How can parameters' values be got inside macro, so that to pass them into mMember->funcname without types?

It is not possible. The typical solution is to pass types and variables in separate arguments and have two separate chains of expansions. This will not work without typedef for function types or array types.

// Macro overloading on number of arguments left for the reader.
// This is a static example for 4 arguments.
#define MYMACRO_ARGS(a, b, c, d)   a b, c d
#define MYMACRO_PARAM(a, b, c, d)  b, d
#define MYMACRO(funcname, ...) \
  void funcname(MYMACRO_ARGS(__VA_ARGS__)) { \
       mMember->funcname(MYMACRO_PARAM(__VA_ARGS__)); \
  }

MYMACRO(function2, double, a, string, b)

Overall, I recommend not doing it. Hiding your code behind a macro will make your code harder to read and maintain. Strongly consider just writing the stuff out, instead of making it very hard for linters, code analyzers, and programmers and confusing yourself with unreadable error messages from the compiler.

Related