开发者

Macro with "placeholder" value

I'm working with a library that includes a set of preprocessor libraries. One of them is a FOR_EACH style macro which iterates over a __VA_ARGS__ and calls a user-provided macro for each argument. The user provided macro is called like: SOME_MACRO(current_arg)

However, the problem is that it only works with user-provided macros that take a single argument. I'm trying to do something special which involves both the name of a struct and each field in the struct. The problem is, this requires two arguments to the macro.

Since the library I'm working with only accepts a unary macro, is there some way to "bind" an additional argument to my macro?

As of now, I have to hardcode the name of the struct in my macro. So, if the struct I'm working with is named Foo, I have to say:

#define MY_MACRO(FIELD) /* do something with &Foo::FIELD */

Is there someway I could "bind" a second STRUCT argument to the macro, perhaps with some further indirection, so that when the library invokes my macro it would be able to expand as:

#define MY_MACRO(FIELD) /* do something with &STRUCT::FIELD */开发者_StackOverflow社区


Yes. You can use following technique.

#define MY_MACRO(FIELD) EXPAND FIELD
#define EXPAND(X, FIELD) X::FIELD()

Usage in the below test code:

struct foo { static int f() { return 0; } };
struct STRUCT { static int f() { return 1; } };

#define MY_MACRO(FIELD) EXPAND FIELD
#define EXPAND(X, FIELD) X::FIELD()

int main ()
{
  int i = MY_MACRO((STRUCT,f)); // see here braces inside braces
}

Above code is expanded to,

int main ()
{
  int i = STRUCT::f();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜