C 中的标记粘贴
阅读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 中阅读了此。但仍然无法让它工作......
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为宏的评估规则。您必须定义某种辅助宏来接收数字作为令牌:
等等。您还可以浏览一下 P99 文档的预发布版本。这将为您提供更舒适的宏工具来直接执行此操作。
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:
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.
PP_NARG
是一件相当令人印象深刻的疯狂事!按照 C99 标准中的
glue
示例(6.10.3.5,示例 4),以下代码会产生所需的结果: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:我没有可用于检查的 C99 编译器,但这应该可以工作:
I don't have a C99 compiler available to check, but this should work: