是否需要将typedef类型设为枚举? [英] Is it required to typedef a primitive type to an enum?

查看:155
本文介绍了是否需要将typedef类型设为枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看 NSString 头文件,以了解Apple如何编写其枚举并发现这段代码:

I was looking through the NSString header file to see how Apple writes their enumerations and came across this piece of code:

enum {
    NSStringEncodingConversionAllowLossy = 1,
    NSStringEncodingConversionExternalRepresentation = 2
};
typedef NSUInteger NSStringEncodingConversionOptions;

这让我有几个问题。


  1. 为什么他们使用匿名枚举?这个方法是有利的吗?

  2. c $ c $ typedef NSUInteger NSStringEncodingConversionOptions; 是一个很好的主意,包括正常,或者只是在这里使用,他们已经宣布匿名枚举?

  1. Why have they used anonymous enumerations? Is this method advantageous?
  2. Is the typedef NSUInteger NSStringEncodingConversionOptions; line a good idea to include normally, or is it only used here because they have declared an anonymous enumeration?


推荐答案

这个奇怪的定义是有明确定义在64位和32位环境中的代码中的枚举的位宽和带符号。在这个苹果文档,但是让我在这里写下摘要。

That strange-looking definition is there to clearly define the bit-width and the signed-ness of an enum in a code both in 64-bit and 32-bit environment. It's detailed in this Apple document, but let me write down the summary here.

以前,苹果使用了标准的typedef枚举,在

Apple in the past used the standard typedef enums before, as in

typedef enum { .... } NSEnumTypeName;

(我使用re,因为自从NeXTStep天以来,FAT二进制文件已经在那里了。)

before 64bit-32bit universal binaries were (re)introduced. (I used "re" because the FAT binaries have been there since the NeXTStep days. Anyway.)

然而,这使得位宽和签名typedef'd类型 NSEnumTypeName 按照官方标准,见6.7.2.2.4。

However, this makes the bit-width and the signed-ness of the typedef'd type NSEnumTypeName to be implementation-defined as specified in the Official Standard, see 6.7.2.2.4.

这使得它更加棘手写一个可以用各种编译器和各种位宽编译的代码。

That makes it even trickier to write a code which can be compiled with various compilers and with various bit-width.

所以苹果从标准枚举转换为具有相应typedef的匿名枚举有符号/无符号整数类型。

So Apple switched from the standard enum to the anonymous enum with a corresponding typedef to a specific signed/unsigned integer type.

这篇关于是否需要将typedef类型设为枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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