什么是## preprocessor运营商和陷阱要考虑的应用程序? [英] What are the applications of the ## preprocessor operator and gotchas to consider?

查看:184
本文介绍了什么是## preprocessor运营商和陷阱要考虑的应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为我的很多previous问题提到的,我通过K&放工作; R,和我目前到preprocessor。其中一个更有趣的事情—东西我从来没有从我的任何尝试之前学习C&MDASH之前就知道;是 ## preprocessor运营商。根据K&安培; R:

As mentioned in many of my previous questions, I'm working through K&R, and am currently into the preprocessor. One of the more interesting things — something I never knew before from any of my prior attempts to learn C — is the ## preprocessor operator. According to K&R:

在preprocessor运营商 ##
  提供了一种方法来连接实际
  宏扩展过程中的参数。如果一个
  在替换文本参数
  毗邻 ## ,参数
  通过实际参数取代,
   ## 和周围的白色空间中
  取出,并将其结果进行重新扫描。
  例如,宏粘贴
  会将其两个参数:

The preprocessor operator ## provides a way to concatenate actual arguments during macro expansion. If a parameter in the replacement text is adjacent to a ##, the parameter is replaced by the actual argument, the ## and surrounding white space are removed, and the result is re-scanned. For example, the macro paste concatenates its two arguments:

的#define贴(前,后)前##回

所以粘贴(姓名,1)创建令牌
  名1

如何以及为什么会有人在现实世界中使用它?它有什么用实际的例子,以及是否有陷阱的考虑?

How and why would someone use this in the real world? What are practical examples of its use, and are there gotchas to consider?

推荐答案

CrashRpt:使用##到宏观的多字节字符串转换为统一code

在CrashRpt(崩溃报告库)一个有趣的用法如下:

An interesting usage in CrashRpt (crash reporting library) is the following:

#define WIDEN2(x) L ## x
#define WIDEN(x) WIDEN2(x)
//Note you need a WIDEN2 so that __DATE__ will evaluate first.

下面他们想用一个两字节串而不是一个字节的每字符串。这可能看起来是真的毫无意义,但他们是一个很好的理由。

Here they want to use a two-byte string instead of a one-byte-per-char string. This probably looks like it is really pointless, but they do it for a good reason.

 std::wstring BuildDate = std::wstring(WIDEN(__DATE__)) + L" " + WIDEN(__TIME__);

它们使用它与返回的日期和时间的字符串另一个宏

They use it with another macro that returns a string with the date and time.

旁边有一个 __ __ DATE 会给你一个编译错误。

Putting L next to a __ DATE __ would give you a compiling error.

Windows系统:使用##为通用的统一code和多字节字符串

Windows使用类似以下内容:

Windows uses something like the following:

#ifdef  _UNICODE
    #define _T(x)      L ## x
#else
    #define _T(x) x
#endif

_T 到处使用code

各种库,使用清洁的访问和修改名称:

我也看到了它在code用来定义访问和修改:

I've also seen it used in code to define accessors and modifiers:

#define MYLIB_ACCESSOR(name) (Get##name)
#define MYLIB_MODIFIER(name) (Set##name)

同样,你可以使用任何其他类型的巧名创建的这个方法相同。

Likewise you can use this same method for any other types of clever name creation.

各种库,用它来一次做出几个变量声明:

#define CREATE_3_VARS(name) name##1, name##2, name##3
int CREATE_3_VARS(myInts);
myInts1 = 13;
myInts2 = 19;
myInts3 = 77;

这篇关于什么是## preprocessor运营商和陷阱要考虑的应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆