Enumerations

Scoped Enumerations C++11

enum class name { enumerator1, enumerator2, ..., enumeratorN };

default: each enumerator is mapped to a whole number from 0 to N-1

enum class day { mon, tue, wed, thu, fri, sat, sun };
day d = day::mon;
d = day::tue; // RIGHT!
d = wed; // WRONG! COMPILER ERROR: 'wed' only known in day's scope
  • enumerators confined to a named scope
  • cannot query properties of enumeration as in some other languages

Unscoped enumerations

enum name { enumerator1, enumerator2, … enumeratorN };

note the absence of keyword “class”

enum day { mon, tue, wed, thu, fri, sat, sun };
day d = mon; // OK!, enumerator "mon" unscoped
int i = wed; // OK!, i = 2
enum stars { sun, … }; // WRONG! COMPILER ERROR: name collision
  • enumerators not confined to a scope ⇒ name collisions
  • dangerous implicit conversion to underlying type
  • cannot query properties of enumeration as in some other languages
  • avoid unscoped enumerations

Underlying Type Of Enumerations

  • must be an integer type (char, short, long, …)
  • int is the default
// 7 values ⇒ char should be enough
enum class day : char {
mon, tue, wed, thu, fri, sat, sun
};
// less than 10,000 ⇒ short should be enough
enum class language_ISO639 : short {
abk, aar, afr, aka, amh, ara, arg, …
};

Custom Enumerator Mapping

  • enumerator values can be set explicitly
  • need not start with 0
  • some values can be left out
  • can be partial (only some enumerators with expl. value)
  • if you set enumerator values explicitly, do it for all enumerators
enum class month {
jan = 1, feb = 2, mar = 3, apr = 4, may = 5, jun = 6,
jul = 7, aug = 8, sep = 9, oct = 10, nov = 11, dec = 12
};
enum class flag {
A = 2, B = 8, C = 5, D, E, F = 25
};

Conversions To/From Underlying Type

enum class month {
jan = 1, feb = 2, mar = 3, apr = 4, may = 5, jun = 6,
jul = 7, aug = 8, sep = 9, oct = 10, nov = 11, dec = 12
};

Enum → Integer

int i = static_cast<int>(month::mar);  
// i: 3

Integer → Enum

int i = 0;
cin >> i;
// make sure i ≥ 1 and ≤ 12 …
month m1 = static_cast<month>(i);

References

https://hackingcpp.com/cpp/lang/enumerations.html