现在的位置: 首页 > 综合 > 正文

宏:##-合并操作符

2018年04月04日 ⁄ 综合 ⁄ 共 1843字 ⁄ 字号 评论关闭

原文出处:http://msdn.microsoft.com/en-us/library/09dwwt6y(VS.80).aspx

试着翻译了msdn上的一段说明文档,有好些地方译的自己也不满意,欢迎大家批评指正。

 

The double-number-sign or "token-pasting" operator (##), which is sometimes called the "merging" operator, is used in both object-like and function-like macros. It permits separate tokens to be joined into a single token and therefore cannot be the first or last token in the macro definition.

##,双数符号又称标志超出操作符(token-pasting" operator ),有时也叫做合并操作符,在定义作用类似对象和函数的宏时需要用到。它可以做到让分开的标志合并为单独的标志,因此,它不能是宏定义中的第一个或最后一个标志。

 

 

If a formal parameter in a macro definition is preceded or followed by the token-pasting operator, the formal parameter is immediately replaced by the unexpanded actual argument. Macro expansion is not performed on the argument prior to replacement.

在宏定义中如果一个正式的参数的前面或后面有合并操作符,这个正式的参数立即会被当前还没展开的变量替代。在这个替换之前,不会进行宏展开。

 

 

Then, each occurrence of the token-pasting operator in token-string is removed, and the tokens preceding and following it are concatenated. The resulting token must be a valid token. If it is, the token is scanned for possible replacement if it represents a macro name. The identifier represents the name by which the concatenated tokens will be known in the program before replacement. Each token represents a token defined elsewhere, either within the program or on the compiler command line. White space preceding or following the operator is optional.

然后,合并操作符在标志符串的每次出现都被去掉了,前后的标志符因此被连接起来了。形成的标志必须是一个有效的标志。如果是有效的标志,这个标志将会被扫描判断,如果它表示一个宏名,它将会被替换。这个识别符表示一个名字:通过这个名字,连接成的标志在程序中被替换前将会被识别,每个标志表示一个在程序中或在编译命令行中已经定义过的标志。标志前后的空格是随意的。

 

 

This example illustrates use of both the stringizing and token-pasting operators in specifying program output:

下面这个例子展示了字符串化操作符和合并操作符在规定程序输出上的用处:

#define paster( n ) printf_s( "token" #n " = %d", token##n )

int token9 = 9;

paster( 9 );

 

the macro yields:这个宏将替换为:

printf_s( "token" "9" " = %d", token9 );

接着变为:

printf_s( "token9 = %d", token9 );

 

一个完整的例子:

// preprocessor_token_pasting.cpp

#include <stdio.h>

#define paster( n ) printf_s( "token" #n " = %d", token##n )

int token9 = 9;

 

int main()

{

   paster(9);

}

 

输出:token9 = 9

抱歉!评论已关闭.