Token pasting in C

爱⌒轻易说出口 提交于 2019-12-22 05:15:21

问题


After reading about VA_NARG

I tried to implement function overloading depending on number of arguments in C using macros. Now the problem is:

void hello1(char *s) { ... }
void hello2(char *s, char *t) { ... }
// PP_NARG(...)           macro returns number of arguments :ref to link above
 // does not work
#define hello(...)         hello ## PP_NARG(__VA_ARGS__)  

int main(void)
{
   hello("hi");   // call hello1("hi");
   hello("foo","bar"); // call hello2("foo","bar");
   return 0;
}

I've read this from C-faq. But still could not get it to work...


回答1:


This is because of the evaluation rules for macros. You would have to define some sort of helper macro that receives the number as a token:

#define HELLO_1(N, ...)         hello ## N
#define HELLO_0(N, ...)         HELLO_1(N, __VARGS__)
#define HELLO(...)         HELLO_0(PP_NARG(__VA_ARGS__), __VARGS__)  

or so. You could also have a glance into the prerelease of the documentation of P99. This will provide you more comfortable macro tools to do that directly.




回答2:


That PP_NARG is a rather impressive piece of craziness!

Following the glue example in the C99 standard (6.10.3.5, example 4), the following produces the desired results:

#define glue(a, b)   a ## b
#define xglue(a, b)  glue(a, b)

#define hello(...)   xglue(hello, PP_NARG(__VA_ARGS__))(__VA_ARGS__)



回答3:


I don't have a C99 compiler available to check, but this should work:

#define helloN(N, ...) hello ## N (__VA_ARGS__)
#define hello(...) helloN(PP_NARG(__VA_ARGS__), __VA_ARGS__)


来源:https://stackoverflow.com/questions/3769381/token-pasting-in-c

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