C 中的标记粘贴

发布于 2024-09-24 15:03:46 字数 701 浏览 1 评论 0原文

阅读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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

说好的呢 2024-10-01 15:03:46

这是因为宏的评估规则。您必须定义某种辅助宏来接收数字作为令牌:

#define HELLO_1(N, ...)         hello ## N
#define HELLO_0(N, ...)         HELLO_1(N, __VARGS__)
#define HELLO(...)         HELLO_0(PP_NARG(__VA_ARGS__), __VARGS__)  

等等。您还可以浏览一下 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:

#define HELLO_1(N, ...)         hello ## N
#define HELLO_0(N, ...)         HELLO_1(N, __VARGS__)
#define HELLO(...)         HELLO_0(PP_NARG(__VA_ARGS__), __VARGS__)  

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.

弱骨蛰伏 2024-10-01 15:03:46

PP_NARG 是一件相当令人印象深刻的疯狂事!

按照 C99 标准中的 glue 示例(6.10.3.5,示例 4),以下代码会产生所需的结果:

#define glue(a, b)   a ## b
#define xglue(a, b)  glue(a, b)

#define hello(...)   xglue(hello, PP_NARG(__VA_ARGS__))(__VA_ARGS__)

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:

#define glue(a, b)   a ## b
#define xglue(a, b)  glue(a, b)

#define hello(...)   xglue(hello, PP_NARG(__VA_ARGS__))(__VA_ARGS__)
樱桃奶球 2024-10-01 15:03:46

我没有可用于检查的 C99 编译器,但这应该可以工作:

#define helloN(N, ...) hello ## N (__VA_ARGS__)
#define hello(...) helloN(PP_NARG(__VA_ARGS__), __VA_ARGS__)

I don't have a C99 compiler available to check, but this should work:

#define helloN(N, ...) hello ## N (__VA_ARGS__)
#define hello(...) helloN(PP_NARG(__VA_ARGS__), __VA_ARGS__)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文