开发者

C/C++ Macro expansion : from two to four parameters

I'm trying to convert a two parameter macro into a four parameter one. From the definition of LIST which I can't change, I'd like to call ALL, providing the two extra parameters.

#define LIST(x) \
   x(p1, p2)    \
   x(p3, p4)    \
   x(...

#define ALL(A, B, C, D) .../... do stuff with A, B, C and D

Here's what I tried so far:

#define RIGHT(C, D) C, D)
#define LEFT(A, B) (A, B, RIGHT

But when I'm testing it (gcc -E text.cpp) with LIST( ALL LEFT (q1, q2) ) I get the following error:

error: unterminated argument list invoking macro "ALL"

Taking a closer look at it, this is why:

  1. LIST is substituted which give for the first line ALL LEFT (q1, q2)(p1, p2)
  2. LEFTis substituted to ALL (q1, q2, RIGHT(p1, p2)
  3. 开发者_JS百科
  4. The preprocessor tries to expand ALL, but doesn't find the closing parenthesis, there's the error...

How can I do otherwise?

Thanks.

EDIT:

To be more precise, with the given input:

#define LIST(x) \
   x("p1", "p2")    \
   x("p3", "p4")    \
   x("p5", "p6")
#define ALL(A, B, C, D) {A, B, C, D}

I want to find a way to get, as a result:

{"q1", "q2", "p1", "p2"}
{"q1", "q2", "p3", "p4"}
{"q1", "q2", "p5", "p6"}


I see two anwers to this:

1) Pass in the name of a helper macro when using LIST:

#define to_all(c, d) ALL("q1", "q2", c, d)
LIST(to_all)

2) Let LIST expand to helper macros, which is expected to exist when used (this is a variant of something named x-macros). This, however, would require you to redefine list:

// Somewhere "central"
#define LIST() \
   LIST_HELPER("p1", "p2")    \
   LIST_HELPER("p3", "p4")    \
   LIST_HELPER("p5", "p6")
#define ALL(A, B, C, D) {A, B, C, D}

// When used:
#define LIST_HELPER(c, d) ALL("q1", "q2", c, d)
LIST()
#undef LIST_HELPER
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜