开发者

Is the use of previously defined members as part of later members in an enum definition legal?

开发者 https://www.devze.com 2022-12-09 17:45 出处:网络
namespace ValueType { enum Enum { Boolean = 0, Float = 1, Double, SInt = 8, SLong, UInt = SInt + (1 <<4),
namespace ValueType {
  enum Enum {
    Boolean = 0,
    Float = 1,
    Double,
    SInt = 8,
    SLong,
    UInt = SInt + (1 <<4),
    ULong = SLong + (1开发者_如何学Go << 4)
  };
}


Yes -- the requirement is that it's an integral constant expression. The C++ standard includes the following example:

enum { d, e, f=e+2 };


As pointed out by Jerry, it is legal.

In some rare cases its wroth being aware that the type of the enumerators are only specified after the enumeration is fully defined. The standard says the following about the type of the enumerations (7.2/4):

Each enumeration defines a type that is different from all other types. Following the closing brace of an enum-specifier, each enumerator has the type of its enumeration. Prior to the closing brace, the type of each enumerator is the type of its initializing value. If an initializer is specified for an enumerator, the initializing value has the same type as the expression. If no initializer is specified for the first enumerator, the type is an unspecified integral type. Otherwise the type is the same as the type of the initializing value of the preceding enumerator unless the incremented value is not representable in that type, in which case the type is an unspecified integral type sufficient to contain the incremented value.

The highlighted sentence can be shown in the following example:

enum E {
  E0            // Unspecified type
  , E1 = E0-1   // -1, or MAX_UINT
  , E2          // 0 or (MAX_UINT+1)
};

Basically, the type chosen for E0 affects the resulting value of E1.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号