具有可变数量参数的 C++ 宏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5283197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:49:20  来源:igfitidea点击:

C++ macro with variable number of arguments

c++macros

提问by Mircea Ispas

Possible Duplicate:
C/C++: How to make a variadic macro (variable number of arguments)

可能的重复:
C/C++:如何制作可变参数宏(可变数量的参数)

I need macro that will expand in a array that contains it's arguments. For example:

我需要将在包含它的参数的数组中展开的宏。例如:

#define foo(X0) char* array[1] = {X0}
#define foo(X0, X1) char* array[2] = {X0, X1}

and so on. My problem is that I need to use foo with variable number of arguments, so I want to be able to use foo("foo0") but also to use foo("foo0", "foo1", "foo2"..."fooN"). I know it's possible to have:

等等。我的问题是我需要使用 foo 和可变数量的参数,所以我希望能够使用 foo("foo0") 但也可以使用 foo("foo0", "foo1", "foo2"..." fooN”)。我知道可能有:

#define foo(...)
#define foo_1(X0) ..
#define foo_2(X0, X1) ..
#define foo_3(X0, X1, X2) ..
#define foo_N(X0, X1, ... XN) ..

And use ____VA_ARGS____, but I don't know how may I expand foo in foo_k macro depending on it's parameter count? Is this possible?

并使用 ____VA_ARGS____,但我不知道如何根据它的参数计数在 foo_k 宏中扩展 foo ?这可能吗?

回答by JoeSlav

How about:

怎么样:

#define FOO( ... ) char* x[] = { __VA_ARGS__ };

回答by Paul R

This should work:

这应该有效:

#define foo(args...) char* array[] = {args}

Note that this uses a GNU extension and so will only work with gcc and gcc-compatible compilers. @JoeSlav's answer using __VA_ARGS__is more portable.

请注意,这使用了 GNU 扩展,因此只能与 gcc 和 gcc 兼容的编译器一起使用。@JoeSlav's answer using__VA_ARGS__更便携。

回答by karlphillip

I recommend gcc.gnu.org docson the subject.

我推荐关于这个主题的gcc.gnu.org 文档

Or you could jump straight away to this answer:

或者你可以直接跳到这个答案:

How to make a variadic macro (variable number of arguments)

如何制作可变参数宏(可变数量的参数)