Search code examples
c++visual-studioenumsenumeration

enum [tag] [: type] {enum-list} [declarator] in C++ - is this legal?


I am working with a custom enumerated type in C++, but it does not have many values. I want to try to reduce the size that they take up, and I've heard that enum types are always integers by default. I then came across the MSDN entry on C++ enumerations, and found the following syntax very interesting:

enum [: type] {enum-list};

Sure enough, it compiled with what I wanted (VS2008) when I did the following:

enum plane : unsigned char { xy, xz, yz };

Now, you can see from my enumeration constants that I don't need much in terms of space - an unsigned char type would be perfect for my uses.

However, I have to say, I've never seen this form used anywhere else on the internet - most don't even seem aware of it. I'm trying to make this code cross-platform (and possibly for use on embedded systems), so it left me wondering... Is this proper C++ syntax, or only supported by the MSVC compiler?

Edit: It seems that this feature is now part of C++11 and above, and is called scoped enumerations.


Solution

  • As 0A0D's said, the notation you're using is non-Standard in C++03, but has been adopted by C++11 under the term "scoped enums".

    If that's not soon enough for you, then you can consider explicitly specifying the bit field width used for the enum fields in the size-critical structures in which they're embedded. This approach is ugly - I mention if for completeness; if it was a good solution the notation above wouldn't be being adopted for C++11. One problem is that you rely on an optional compiler warning to detect too-small bit-fields to hold the possible values, and may have to manually review them as the enumeration values change.

    For example:

    enum E
    {
        A, B, C
    };
    
    struct X
    {
        E e1 : 2;
        E e2 : 2;
        E e3 : 2;
        E e4 : 2;
    };
    

    Note: the enum may occupy more bits than requested - on GCC 4.5.2 with no explicit compiler options, sizeof(X) above is still 4....