c – 为什么我需要双层的间接宏?

在:C++ FAQ – Miscellaneous technical issues – [39.6] What should be done with macros that need to paste two tokens together?

有人可以向我解释为什么吗?我读的都是相信我,但我根本就不能信任某事,因为有人这么说。

我尝试了这种方法,我找不到任何错误出现:

#define mymacro(a) int a ## __LINE__
mymacro(prefix) = 5;
mymacro(__LINE__) = 5;
int test = prefix__LINE__*__LINE____LINE__; // fine

那么为什么我需要这样做呢(从网页引用):

However you need a double layer of indirection when you use ##.
Basically you need to create a special macro for “token pasting” such
as:

06001

Trust me on this — you really need to do
this! (And please nobody write me saying it sometimes works without
the second layer of indirection. Try concatenating a symbol with
__ LINE__ and see what happens then.)

编辑:有人也可以解释为什么他在下面声明NAME2_HIDDEN?在使用它之前定义NAME2_HIDDEN宏似乎更合乎逻辑。这里有什么技巧吗?

C规范的相关部分:

6.10.3.1 Argument substitution

After the arguments for the invocation of a function-like macro have been identified,
argument substitution takes place. A parameter in the replacement list, unless preceded
by a # or ## preprocessing token or followed by a ## preprocessing token (see below), is
replaced by the corresponding argument after all macros contained therein have been
expanded. Before being substituted, each argument’s preprocessing tokens are
completely macro replaced as if they formed the rest of the preprocessing file; no other
preprocessing tokens are available.

确定您是否要双重间接的关键部分是第二个句子和其中的异常 – 如果参数涉及#或##操作(例如mymacro和NAME2_HIDDEN中的参数),则任何其他在#或##之前,参数中的宏不会被扩展。另一方面,如果在宏体中没有#或##(与NAME2一样),则扩展参数ARE中的​​其他宏。

所以它归结于你想要的 – 有时你想要所有的宏扩展FIRST,然后做#或##(在这种情况下你想要双层间接),有时你不想让宏首先扩展(其中你不能拥有双层宏,你需要直接做到这一点。)

http://stackoverflow.com/questions/8231966/why-do-i-need-double-layer-of-indirection-for-macros

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:c – 为什么我需要双层的间接宏?