具有零参数和逗号的可变参数宏
考虑这个宏:
#define MAKE_TEMPLATE(...) template <typename T, __VA_ARGS__ >
当与零参数一起使用时,它会产生错误的代码,因为编译器期望逗号后面有一个标识符。实际上,VC 的预处理器足够聪明,可以删除逗号,但 GCC 的则不然。 由于宏不能重载,因此对于这种特殊情况似乎需要一个单独的宏才能使其正确,例如:
#define MAKE_TEMPLATE_Z() template <typename T>
有什么方法可以使其在不引入第二个宏的情况下工作吗?
Consider this macro:
#define MAKE_TEMPLATE(...) template <typename T, __VA_ARGS__ >
When used with zero arguments it produces bad code since the compiler expects an identifier after the comma. Actually, VC's preprocessor is smart enough to remove the comma, but GCC's isn't.
Since macros can't be overloaded, it seems like it takes a separate macro for this special case to get it right, as in:
#define MAKE_TEMPLATE_Z() template <typename T>
Is there any way to make it work without introducing the second macro?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,因为宏调用
MAKE_TEMPLATE()
根本没有零参数;它有一个由零个标记组成的参数。较旧的预处理器(显然包括最初编写此答案时的 GCC)有时会按照您的希望解释空参数列表,但共识已转向更严格、更窄的扩展,更符合标准。
要使下面的答案起作用,请在省略号之前定义一个附加宏参数:
然后当列表不为空时,始终在第一个参数之前放置一个逗号:
旧答案
根据 http://gcc.gnu.org/onlinedocs/gcc/Variadic-Macros.html,GCC 确实支持这一点,只是不支持透明地。
语法是:
无论如何,两者都支持 C++0x 模式下的可变参数模板,这是更可取的。
No, because the macro invocation
MAKE_TEMPLATE()
does not have zero arguments at all; it has one argument comprising zero tokens.Older preprocessors, apparently including GCC at the time this answer was originally written, sometimes interpreted an empty argument list as you'd hope, but the consensus has moved toward a stricter, narrower extension which more closely conforms to the standard.
To get the answer below to work, define an additional macro parameter before the ellipsis:
and then always put a comma before the first argument when the list is not empty:
Old answer
According to http://gcc.gnu.org/onlinedocs/gcc/Variadic-Macros.html, GCC does support this, just not transparently.
Syntax is:
Anyway, both also support variadic templates in C++0x mode, which is far preferable.
如果是 GCC,您需要这样写:
如果 __VA_ARGS__ 为空,GCC 的预处理器会删除前面的逗号。
In case of GCC you need to write it like this:
If
__VA_ARGS__
is empty, GCC's preprocessor removes preceding comma.首先要注意,可变参数宏不是当前 C++ 的一部分。看来他们会在下一个版本中出现。目前,仅当您使用 C99 编程时,它们才符合要求。
对于零参数的可变参数宏,有一些技巧可以检测到它并围绕它进行宏编程。 Google 搜索空宏参数。
First of all beware that variadic macros are not part of the current C++. It seems that they will be in the next version. At the moment they are only conforming if you program in C99.
As of variadic macros with zero arguments, there are tricks à la boost to detect this and to macro-program around it. Googel for empty macro arguments.