用C标记粘贴 [英] Token pasting in C

查看:167
本文介绍了用C标记粘贴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读 VA_NARG <后/ A>

我想这取决于 C 使用宏数量的参数来实现函数重载。
现在的问题是:

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;
}

我读过从C-FAQ。但还是没能得到它的工作...

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

推荐答案

这是因为宏的评价规则。你必须定义一些辅助宏接收数量为令牌:

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__)  

左右。你也可以有一个一目了然进入 P99的文件。这将为您提供更舒适的宏观工具直接做到这一点。

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.

这篇关于用C标记粘贴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆