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)
2
  • 2
    What blocks you not to use a template helper function (i.e. template<typename MemFunction, typename... Args> void helper(const MemFunction& func, Args&&... args){ ... }) for this instead of macro? And use std::invoke to invoke the functions more generic way. Commented Jul 23, 2021 at 11:29
  • 2
    Or, if you really need to keep this interface, you could still do it with macro: #define MYMACRO(funcname) template <typename... Args> void funcname(Args... args) { mMember->funcname(std::forward(args)); } Commented Jul 23, 2021 at 11:35

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.