Concatenation of tokens in variadic macros

不想你离开。 提交于 2019-12-07 15:55:34

问题


In C, is it possible to concatenate each of the variable arguments in a a variadic macro?

Example:

MY_MACRO(A, B, C) // will yield HDR_A, HDR_B, HDR_C
MY_MACRO(X, Y)    // will yield HDR_X, HDR_Y

The normal ## operator has special meaning for variadic macros (avoiding the comma for empty argument list). And concatenation when used with __VA_ARGS__ takes place with the first token only.

Example:

#define MY_MACRO(...) HDR_ ## __VA_ARGS__

MY_MACRO(X, Y)    // yields HDR_X, Y

Suggestions?


回答1:


First, the comma rule you are mentioning is a gcc extension, standard C doesn't have it and most probably will never have it since the feature can be achieved by different means.

What you are looking for is meta programming with macros, which is possible, but you'd need some tricks to achieve that. P99 provides you with tools for that:

#define MY_PREFIX(NAME, X, I) P99_PASTE2(NAME, X)
#define MY_MACRO(...) P99_FOR(HDR_, P99_NARG(__VA_ARGS__), P00_SEQ, MY_PREFIX, __VA_ARGS__)
  • Here MY_PREFIX describes what has to be done with the individual items.
  • P00_SEQ declares how the items should be separated
  • P99_NARGS just counts the number of arguments


来源:https://stackoverflow.com/questions/10458402/concatenation-of-tokens-in-variadic-macros

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!