8

I have an inline variadic function
inline int foo(...)
I need foo() to call a macro (let's call it MACRO), which is also variadic.
Basically I need foo() to pass all its input parameters to MACRO. Redefining foo() as another macro would be an easy solution because of __VA_ARGS__ option, but I also need foo() to return a value.
Note: I am trying to interface two parts of already written code and I am not allowed to change them. foo(...) is used in the first part of code and MACRO is defined in the second part. Only thing I am supposed to do is to define a foo() which uses MACRO and I can't because they are both variadic.

The Vivandiere
  • 3,059
  • 3
  • 28
  • 50
lulijeta
  • 900
  • 1
  • 9
  • 19
  • Can you use variadic template for `foo` instead of ellipsis ? – Jarod42 Apr 29 '15 at 16:08
  • Are you talking about varargs or variadic function templates ? With one your problem can be solved, with the other it can't. – Quentin Apr 29 '15 at 16:08
  • 4
    Can't be done. Function parameters are set at run-time, macros are expanded before compilation. I'd throw this mess away and figure out a sensible way of doing whatever it's trying to do. – Mike Seymour Apr 29 '15 at 16:10
  • I am not familiar with variadic templates sir, let me check – lulijeta Apr 29 '15 at 16:11
  • yes, I can use variadic template for foo, but I couldn't get it to compile when I pass the input parameters to the variadic macro – lulijeta Apr 30 '15 at 08:11
  • Could you show `MACRO` ? Does it substitution is broken with `args...` ? – Jarod42 May 02 '15 at 21:29

2 Answers2

7

Make foo a macro that contains a lambda that returns a value, and then invokes that lambda.

#define foo(...) \
  [&](auto&&...args){ \
    /* do something with args, or __VA_ARGS__ */ \
    MACRO(__VA_ARGS__); \
    return 7; \
  }(__VA_ARGS__)

now int x = foo(a, b, c); will both call the lambda inside foo, and inside that lambda call the macro on (a, b, c), and can return a value.

I pity whomever maintains your code next.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
  • 1
    Note that `args...` and `__VA_ARGS__` may differ for cases like `foo(arg1, (extra, parenthesis, around, comma, operator, arg2));` or simple `foo(function_with_side_effect())`. – Jarod42 May 05 '15 at 17:09
  • 1
    @Jarod42 yep! The `auto&&....args` and `(__VA_ARGS__)` is optional, and can cause unpredictable side effects. Still, it gives you the arguments as arguments, as well as as tokens, which I figure is what the OP wanted. – Yakk - Adam Nevraumont May 05 '15 at 17:12
2

What you're asking is impossible.

A variadic function's arguments are determined at runtime, but a macro expands at compile time.

orlp
  • 112,504
  • 36
  • 218
  • 315