Nya*_*yan 6 c c99 stringification c-preprocessor variadic-macros
看完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;
}
Run Code Online (Sandbox Code Playgroud)
我从C-faq那里读到了这个.但仍然无法让它工作......
这是因为宏的评估规则。您必须定义某种辅助宏来接收数字作为令牌:
#define HELLO_1(N, ...) hello ## N
#define HELLO_0(N, ...) HELLO_1(N, __VARGS__)
#define HELLO(...) HELLO_0(PP_NARG(__VA_ARGS__), __VARGS__)
Run Code Online (Sandbox Code Playgroud)
或者。您还可以浏览一下P99文档的预发布。这将为您提供更舒适的宏工具来直接执行此操作。