4

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)
cigien
  • 57,834
  • 11
  • 73
  • 112
shtirlic
  • 41
  • 1
  • 2
    What blocks you **not to use** a template helper function (i.e. `template void helper(const MemFunction& func, Args&&... args){ ... }`) for this instead of macro? And use [`std::invoke`](https://en.cppreference.com/w/cpp/utility/functional/invoke) to invoke the functions more generic way. – JeJo Jul 23 '21 at 11:29
  • 2
    Or, if you really need to keep this interface, you could still do it with macro: `#define MYMACRO(funcname) template void funcname(Args... args) { mMember->funcname(std::forward(args)); }` – Yksisarvinen Jul 23 '21 at 11:35

1 Answers1

0

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.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111