How to remove the enclosing parentheses with macro

2019-02-06 12:28发布

问题:

No comma is allowed in a macro argument because it will be treated as more than one arguments and the preprocessing will be wrong. However, we can parenthesize the argument to let preprocessor treat it as one argument. Is there a macro or other techniques which can remove the enclosing parentheses?

For example, if I define a macro like

#define MY_MACRO(a, b)   ...

and use it like

MY_MACRO( A<int, double>, text );

will be wrong. use it like

MY_MACRO( (A<int, double>), text)

with a macro or technique to remove the parentheses will be fine. Boost provides BOOST_IDENTITY_TYPE macro for only types but not general cases

回答1:

#define ESC(...) __VA_ARGS__

then

MY_MACRO( ESC(A<int, double>), text );

might do what you want.



回答2:

This macro trick is similar to Yakk's solution but removes the need to explicitly pass in another macro as a parameter.

#include <stdio.h>

#define _Args(...) __VA_ARGS__
#define STRIP_PARENS(X) X
#define PASS_PARAMETERS(X) STRIP_PARENS( _Args X )

int main()
{
  printf("without macro %d %d %d %d %d %d\n", (5,6,7,8,9,10) ); // This actually compiles, but it's WRONG
  printf("with macro %d %d %d %d %d %d\n", PASS_PARAMETERS((5,6,7,8,9,10)) ); //Parameter "pack" enclosed in parenthesis
  return 0;
}

Of course you could get creative by making the PASS_PARAMETERS macro into a variadic macro and pass in multiple parameter packs.



回答3:

A simple hack could be to use variadic macros:

#define MY_MACRO(a, b...)   ...

Then you can use it like:

MY_MACRO(text, A<int, double>)

The comma in the second argument is still interpreted as the argument separator (meaning the macro is actually called with three arguments), but it's expanded inside the macro, making the behavior the same. The variadic argument has to be last in the macro, however.