粘贴标记时出现意外的预定义宏行为

以下(用gcc -E blah.c测试):

 #define UNUSED(type) type UNUSED_ ## __COUNTER__ UNUSED(char const *) UNUSED(int) 

产生:

 char const * UNUSED__COUNTER__ int UNUSED__COUNTER__ 

我期待着:

 char const * UNUSED0 int UNUSED1 

我试过调用另一个宏,将括号中的参数包装起来无济于事。 如果我不粘贴令牌,它似乎工作正常。 该文档特别提到在标记粘贴中使用__COUNTER__

我究竟做错了什么?

尝试使用gcc 4.4,这可以:

 #define UNUSED(type) UNUSED_(type, __COUNTER__) #define UNUSED_(type, counter) UNUSED__(type, counter) #define UNUSED__(type, counter) type UNUSED_ ## counter UNUSED(char const *) UNUSED(int) 

但如果我拿出一级中间体,它就不起作用。

__COUNTER__仅在GCC 4.3中引入 – 如果您碰巧使用的是早期版本,则根本没有定义宏。 在这种情况下, Boost.PPs BOOST_PP_COUNTER宏可能值得研究。

在较新的GCC版本中,您仍然需要一种不同的连接方法,因为##阻止其参数扩展。 因此,在使用##之前,必须先将它们展开:

 #define CAT(a, b) CAT_I(a, b) #define CAT_I(a, b) CAT_II(a ## b) #define CAT_II(x) x #define UNUSED(type) type CAT(UNUSED_, __COUNTER__) 

如果您已经在使用Boost, BOOST_PP_CAT()会为您提供相同的function。

我相信你必须“双倍扩大”它:

 #define STR(x) #x #define UNUSED(type) type UNUSED_ ## STR(__COUNTER__) UNUSED(char const *) UNUSED(int)