问题描述
所以我有一个在 GCC 中运行良好的宏,但在 Microsoft 的 C++ 编译器中不起作用.我希望有人可能知道一种解决方法,或者可以向我解释为什么它会这样.
So I've got a macro that works nicely in GCC, but not in Microsoft's C++ Compiler. I'm hoping somebody might know of a workaround, or perhaps can explain to me why it behaves this way.
我确定这个宏并不完全是标准的",但它确实对我有帮助.
I'm sure this macro isn't exactly "standard", but it would really help me out.
这是宏的功能示例:
这里是我可以使用这个宏的方法:
Here is how I might use this macro:
以下是 GCC 如何扩展上述内容:
Here's how GCC expands the above:
但微软出于某种原因将我所有的 __VA_ARGS__ 扩展为一个参数:
But Microsoft for some reason expands all my __VA_ARGS__ as one argument:
有人知道这是为什么吗?有什么技巧可以让微软像 GCC 一样扩展它吗?也许多加几对括号?
Does anybody know why this is? Is there some trick I can pull to get Microsoft to expand this like GCC? Maybe toss in a couple extra pairs of parentheses?
像这样的宏确实可以帮助我替换一堆胶水"代码,但是由于这个问题,我无法将其移动到我的 VS 项目中.任何帮助将不胜感激!
Macros like this could really help me out in replacing a bunch of "glue" code, but because of this problem, I can't move it into my VS project. Any help would be greatly appreciated!
谢谢.
推荐答案
巧合的是,我今天刚好遇到了这个问题,经过足够的努力,我想我已经找到了适合自己的解决方案.错误是 MSVC 将 __VA_ARGS__
视为参数列表中的单个标记.但是您可以通过不在宏调用参数列表中直接使用它来解决此问题.此评论 建议开始回答您的问题:
Coincidentally, I happened to run into this problem just today, and after enough effort I think I've found a solution for my own purposes. The bug is MSVC treats __VA_ARGS__
as a single token in argument lists. But you can work around this by not using it directly within a macro call argument list. This comment suggests the start of an answer to your problems:
但是我怀疑您可能会遇到确保完全扩展到您想要的实际N"的问题,而不是 VA_NARGS_IMPL (arg1, arg2, 5, 4, 3, 2, 1)
,比如说.我发现我的代码(看起来像你的)必须更改以将 MAC##code
全部扩展为一个单元,然后必须将其与参数列表分开组合.这是我发现对我有用的代码:
But then I suspect you'll likely run into the issue of making sure that gets fully expanded to the actual "N" you want, and not to VA_NARGS_IMPL (arg1, arg2, 5, 4, 3, 2, 1)
, say. I found that my code (which looked like yours) had to change to expand MAC##code
all as one unit, and then that had to be separately combined with the argument list. Here's the code that I found worked for me:
在解决了我自己的问题几个小时后,我的思绪太混乱了,无法完全解决你的问题,我很抱歉地说.:-) 但我认为这足以让你做一些有用的事情,只需做一点工作.
My mind is too much mush after a few hours solving my own issues to then go and completely solve yours, I'm sorry to say. :-) But I think this is enough to get you to something that works, with a little work.
这篇关于MSVC++ 可变参数宏扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!