Abusing the C preprocessor

 

在这里Abusing the C preprocessor(http://psomas.wordpress.com/tag/preprocessor/)看到这个C语言宏的使用技巧。把示意代码拷贝出来,稍加修改可以在VS下编译。

至于其中的原理我就不说了,XX后看原文吧。

 

void foo_1(int x){ printf("foo_1 %d\n",x); }

void foo_2(int x,int y){ printf("foo_2 %d %d\n",x,y); }

#define PASTE(a, b) a ## b

#define PASTE2(a, b) PASTE(a, b)

#define NARG_(_9, _8, _7, _6, _5, _4, _3, _2, _1, n, ...) n

#define NARG(...) NARG_(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)

#define foo1(...) foo_1(__VA_ARGS__)

#define foo2(...) foo_2(__VA_ARGS__)

#define foo(...) PASTE2(foo, NARG(__VA_ARGS__)(__VA_ARGS__))

 

int main(void){

foo(32);

foo(12,23);

return 0;

}

 

posted @ 2011-11-29 09:27  嗷嗷  阅读(216)  评论(0编辑  收藏  举报