__VA_ARGS__ expansion using MSVC

99封情书 提交于 2019-12-04 04:27:24

The workaround in question is this:

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

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

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

... to ...

EXPAND( F(1, 2, 3) )

... 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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!