看完约
VA_NARG后
我尝试使用宏根据C中的参数数量实现函数重载.
现在的问题是:
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; }
我从C-faq上读过this.但仍然无法让它工作……
解决方法
这是因为宏的评估规则.您必须定义某种辅助宏,它将数字作为标记接收:
#define HELLO_1(N,...) hello ## N #define HELLO_0(N,...) HELLO_1(N,__VARGS__) #define HELLO(...) HELLO_0(PP_NARG(__VA_ARGS__),__VARGS__)
或者.您还可以浏览一下P99文档的预发布.这将为您提供更加舒适的宏工具来直接执行此操作.