Enums (C++/CX)

C++/CX supports the public enum class keyword, which is analogous to a standard C++ scoped enum. When you use an enumerator that's declared by using the public enum class keyword, you must use the enumeration identifier to scope each enumerator value.

Remarks

A public enum class that doesn't have an access specifier, such as public, is treated as a standard C++ scoped enum.

A public enum class or public enum struct declaration can have an underlying type of any integral type although the Windows Runtime itself requires that the type be int32, or uint32 for a flags enum. The following syntax describes the parts of a public enum class or public enum struct.

This example shows how to define a public enum class:

// Define the enum
public enum class TrafficLight : int { Red, Yellow, Green }; 
// ...

This next example shows how to consume it:

// Consume the enum:
TrafficLight myLight = TrafficLight::Red;
if (myLight == TrafficLight::Green) 
{
    //...
} 

Examples

The next examples show how to declare an enum,

// Underlying type is int32
public enum class Enum1
{
    Zero,
    One,
    Two,
    Three
};

public enum class Enum2
{
    None = 0,
    First,      // First == 1
    Some = 5,
    Many = 10
};

// Underlying type is unsigned int
// for Flags. Must be explicitly specified
using namespace Platform::Metadata;
[Flags]
public enum class BitField : unsigned int 
{
    Mask0 = 0x0,
    Mask2 = 0x2,
    Mask4 = 0x4,
    Mask8 = 0x8
};

Enum1 e1 = Enum1::One;
int v1 = static_cast<int>(e1);
int v2 = static_cast<int>(Enum2::First);

The next example shows how to cast to numeric equivalents, and perform comparisons. Notice that the use of enumerator One is scoped by the Enum1 enumeration identifier, and enumerator First is scoped by Enum2.

 if (e1 == Enum1::One) { /* ... */ }
 //if (e1 == Enum2::First) { /* ... */ } // yields compile error C3063

 static_assert(sizeof(Enum1) == 4, "sizeof(Enum1) should be 4");

 BitField x = BitField::Mask0 | BitField::Mask2 | BitField::Mask4;
 if ((x & BitField::Mask2) == BitField::Mask2) { /*   */ } 

See also

Type System
C++/CX Language Reference
Namespaces Reference