__VA_ARGS__使用MSVC扩展 [英] __VA_ARGS__ expansion using MSVC

查看:108
本文介绍了__VA_ARGS__使用MSVC扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一个问题,该问题显示了如何根据参数数量重载宏: 按参数数量重载宏

I found a question showing how to overload macros based on the number of arguments : Overloading Macro on Number of Arguments

但是正如他们所说,它无法使用MSVC,因为MSVC将__VA_ARGS__扩展为单个标记而不是参数列表(arg1, arg2, arg3).

But as they say, it's not working using MSVC because MSVC expands __VA_ARGS__ into a single token instead of a list of arguments (arg1, arg2, arg3).

他们指出了另一个解决方案:MSVC无法扩展__VA_ARGS__正确 但是完全没有解释,因此我无法理解它,因此我无法适应它.

They point to another question where a work around is given : MSVC doesn't expand __VA_ARGS__ correctly But not explained at all, so I can't adapt it to my own case since I can't understand it.

您能否解释一下该解决方法的工作原理?

Could you please explain how this workaround works ?

推荐答案

有问题的解决方法是:

#define EXPAND( x ) x
#define F(x, ...) X = x and VA_ARGS = __VA_ARGS__
#define G(...) EXPAND( F(__VA_ARGS__) )

这个想法是,给定一个现有的可变参数宏F():

The idea is that given an existing variadic macro F():

#define F(x, ...) X = x and VA_ARGS = __VA_ARGS__

在这种情况下,而不是将所需的可变参数包装宏编写为...

instead of writing your desired variadic wrapper macro as, in this case, ...

#define G(...) F(__VA_ARGS__)

...使用其他EXPAND()宏编写G(). F()的实际定义不是重点,特别是在此示例中,宏扩展不会产生有效的C代码并不重要.其目的是演示预处理程序关于宏参数的行为.具体来说,它表明,尽管MSVC在可变参宏中将__VA_ARGS__扩展为单个令牌,但可以通过强制进行双扩展来解决此问题.

... you write G() with use of the additional EXPAND() macro. The actual definition of F() is not the point, and in particular it doesn't matter for this example that macro expansion does not produce valid C code. Its purpose is to demonstrate the preprocessor's behavior with respect to macro arguments. Specifically, it shows that although MSVC expands __VA_ARGS__ to a single token in a variadic macro, that can be worked around by forcing a double expansion.

例如,使用替代方法定义,预处理器首先扩展...

For example, using the workaround definition, the preprocessor first expands ...

G(1, 2, 3)

...到...

EXPAND( F(1, 2, 3) )

...,其中1, 2, 3被视为单个令牌.当预处理器重新扫描其他替换项时,该标记化不再重要,但是:它将123视为宏F()的单独参数,并根据需要对其进行扩展以生成宏EXPAND(),只是将其替换为自身.

... where the 1, 2, 3 is treated as a single token. That tokenization no longer matters when the preprocessor rescans for additional replacements, however: it sees the 1, 2, 3 as separate arguments to macro F(), and expands that as desired to produce the argument to macro EXPAND(), which just replaces it with itself.

如果您认为这按预期工作很奇怪,但是没有EXPAND()的版本不起作用(在MSVC中),那么您是正确的.

If you think it odd that this works as intended, but the version without EXPAND() does not work (in MSVC), you are right.

这篇关于__VA_ARGS__使用MSVC扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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