Module 4 · Your own types
4.5enum class
Give a short, fixed list of choices its own type: DNA bases, log levels, permission flags. Learn why enum class is safer than a plain enum, how a switch tells you about a missing case, and how to turn an enum into a number or text.
On this page
- Key terms
- In 30 seconds
- Plain enum: named integers
- enum class: a type of its own
- The underlying type
- switch over an enum
- The compiler notices a missing case
- Turning an enum into text
- Enum values as bit flags
- Which one should I use?
- Under the hood
- Common pitfalls
- A default that hides a missing case
- Mixing two plain enums
- Casting any number to an enum
- Try it yourself
Key terms
- enumeration (enum)
- A type whose values come from a fixed list of named constants.
- enumerator
- One of the named values in an enumeration, like
Base::G. - plain
enum(unscoped enum) - The older kind of enumeration. Its names are visible in the whole surrounding scope, and its values turn into
intby themselves. enum class(scoped enum)- An enumeration whose names are written with the type's name in front (
Base::G) and whose values never turn into numbers by themselves. - underlying type
- The integer type an enumeration is stored as.
intfor anenum classunless you choose another with: type. std::to_underlying- A function from
<utility>(C++23) that turns an enum value into its number, in the enum's underlying type. using enum- Makes an enumeration's names usable without the type's name in front, inside the current scope.
-Wswitch- The warning (part of
-Wall) for aswitchover an enum that misses an enumerator and has nodefault.
Some values come from a short list that never changes. A DNA base is A, C, G or T. A log message is a debug message, information, a warning or an error. You could store them as char or int, but then nothing stops a 7 or an 'X' from getting in, and nothing stops you from passing a log level where a base was expected. An enumeration gives the list its own type with a name for each value, and the compiler checks how you use it.
In 30 seconds
enum class Base { A, C, G, T };makes a new type with four named values:Base::A,Base::C,Base::GandBase::T.- An
enum classvalue never turns into a number by itself, and can’t be mixed with another enum. When you need the number, convert on purpose withstd::to_underlyingorstatic_cast. - A
switchover an enum that misses a value gets a warning, which the course’s flags turn into an error. Leave outdefaultso the warning can do its job. - At run time, an enum value is an integer of its underlying type. Choose a small one, like
std::uint8_t, when you store millions of them.
Plain enum: named integers
The older form is a plain enum. Each name, or enumerator, stands for an integer. They count up from 0 in the order you list them.
#include <print>
enum Base { A, C, G, T };
int main() {
Base b = G;
int code = b; // a plain enum turns into an int by itself
std::println("{} {}", code, A + T);
if (b == 2) {
std::println("2 means G");
}
}Output
2 3 2 means G
That’s convenient, but it’s also the problem. A + T and b == 2 compile without a word, though adding two bases makes no sense and 2 could be anything. And the names A, C, G and T now belong to the whole file, not to Base. A second enum that wants a value called A clashes with the first:
enum Base { A, C, G, T };
enum Grade { A, B };
int main() {}The compiler rejects this
main.cpp:2:14: error: ‘A’ conflicts with a previous declaration
2 | enum Grade { A, B };
| ^
main.cpp:1:13: note: previous declaration ‘Base A’
1 | enum Base { A, C, G, T };
| ^enum class: a type of its own
Write enum class instead and both problems go away. The names live inside the type, so you write Base::G, and two enums can each have an A:
#include <print>
enum class Base { A, C, G, T };
enum class Grade { A, B, C };
int main() {
Base b = Base::G;
Grade g = Grade::A;
if (b == Base::G) {
std::println("guanine");
}
if (g != Grade::C) {
std::println("passed");
}
}Output
guanine passed
An enum class value doesn’t turn into a number by itself, so comparing it with an int is a compile error:
enum class Base { A, C, G, T };
Base b = Base::G;
if (b == 2) {
b = Base::A;
}The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:3:7: error: no match for ‘operator==’ (operand types are ‘main()::Base’ and ‘int’)
3 | if (b == 2) {
| ~ ^~ ~
| | |
| | int
| main()::BaseWhen you do need the number, or need to turn a number back into an enum, say so with static_cast from Integers and floating-point numbers:
#include <print>
enum class Base { A, C, G, T };
Base b = Base::T;
int code = static_cast<int>(b);
Base back = static_cast<Base>(2);
std::println("{} {}", code, back == Base::G);Output
3 true
Every conversion to or from a number is written out, where a reader can see it.
The underlying type
Every enum is stored as an integer type, its underlying type. For an enum class it’s int unless you choose another one after a colon. (A plain enum without a colon gets an integer type the compiler picks, big enough for its values.) You can also pick the number for each enumerator with =; the ones you don’t number count up from the one before.
std::to_underlying, from <utility>, turns an enum value into its number, in exactly the underlying type. It’s shorter than static_cast and can’t pick the wrong type.
#include <cstdint>
#include <print>
#include <utility>
enum class Level { debug, info, warning, error };
enum class Base : std::uint8_t { A, C, G, T };
enum class ExitCode { ok = 0, bad_input = 2, no_file };
int main() {
std::println("{} {}", sizeof(Level), sizeof(Base));
std::println("{}", std::to_underlying(Base::T));
std::println("{}", std::to_underlying(ExitCode::no_file));
}Output
4 1 3 3
A Level takes the 4 bytes of an int on this platform. A Base takes 1 byte, because you asked for std::uint8_t. ExitCode::no_file is 3: it counts up from bad_input.
switch over an enum
A switch is the natural way to do something different for each enumerator. Here each case returns, so no break is needed:
#include <print>
enum class Base { A, C, G, T };
char to_char(Base b) {
switch (b) {
case Base::A:
return 'A';
case Base::C:
return 'C';
case Base::G:
return 'G';
case Base::T:
return 'T';
}
return '?'; // b holds a number with no name
}
int main() {
std::println("{}{}", to_char(Base::G), to_char(Base::T));
}Output
GT
The return '?' after the switch isn’t dead code. An enum class with an int underlying type can hold any int, such as static_cast<Base>(9), which has no name. GCC knows this and reports “control reaches end of non-void function” if you leave the last return out.
The compiler notices a missing case
Now say you forget Base::T. The -Wswitch warning, which -Wall turns on, lists every enumerator the switch doesn’t handle. With warnings as errors, it doesn’t compile:
#include <print>
enum class Base { A, C, G, T };
char to_char(Base b) {
switch (b) {
case Base::A:
return 'A';
case Base::C:
return 'C';
case Base::G:
return 'G';
}
return '?';
}
int main() {
std::println("{}", to_char(Base::T));
}The compiler rejects this
main.cpp: In function ‘char to_char(Base)’:
main.cpp:6:12: error: enumeration value ‘T’ not handled in switch [-Werror=switch]
6 | switch (b) {
| ^
cc1plus: all warnings being treated as errorsThis check pays off later. When you add a fifth value to an enum, say N for “unknown base”, every switch that needs a new case stops compiling and points you at it.
Common pitfalldefault turns the check off
-Wswitch stays quiet when the switch has a default label, because default handles every value. In a switch over your own enum, list every case and leave default out; put the fallback after the switch instead.
Writing Level:: on every case gets long. using enum Level; lets you write debug instead of Level::debug until the end of the block it’s in, here the switch. It doesn’t change the type: debug is still a Level, not an int.
#include <print>
enum class Level { debug, info, warning, error };
bool is_problem(Level level) {
switch (level) {
using enum Level;
case debug:
case info:
return false;
case warning:
case error:
return true;
}
return true;
}
int main() {
std::println("{} {}", is_problem(Level::info), is_problem(Level::error));
}Output
false true
Turning an enum into text
The names don’t exist in the running program, and C++23 has no built-in way to turn a value into its name. To print an enum, write a function that returns its name. A switch keeps that function complete, and a std::string_view (from string and string_view) points at the text without copying it.
Going the other way, from text to an enum, can fail, so return a std::optional. parse_level loops over a braced list of every level and returns the one whose name matches:
#include <optional>
#include <print>
#include <string_view>
enum class Level { debug, info, warning, error };
std::string_view to_string(Level level) {
switch (level) {
case Level::debug:
return "debug";
case Level::info:
return "info";
case Level::warning:
return "warning";
case Level::error:
return "error";
}
return "unknown";
}
std::optional<Level> parse_level(std::string_view text) {
for (Level level :
{Level::debug, Level::info, Level::warning, Level::error}) {
if (to_string(level) == text) {
return level;
}
}
return std::nullopt;
}
int main() {
std::println("[{}] disk almost full", to_string(Level::warning));
std::println("{}", parse_level("error") == Level::error);
std::println("{}", parse_level("loud").has_value());
}Output
[warning] disk almost full true false
To print a Level with std::println("{}", level) directly, teach std::println about the type; Operators and comparisons shows how.
Enum values as bit flags
Operators and bit operations stored several yes/no flags in one integer, one bit each. An enum class gives those bits names and a type. Number the enumerators 1, 2, 4, 8, … so each one has its own bit.
The bitwise operators don’t work on an enum class by themselves:
#include <cstdint>
enum class Perm : std::uint8_t { none = 0, read = 1, write = 2, run = 4 };
Perm perms = Perm::read | Perm::write;The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:4:25: error: no match for ‘operator|’ (operand types are ‘main()::Perm’ and ‘main()::Perm’)
4 | Perm perms = Perm::read | Perm::write;
| ~~~~~~~~~~ ^ ~~~~~~~~~~~
| | |
| main()::Perm main()::PermDefine the ones you need. Each one converts to the underlying type with std::to_underlying, does the bit operation, and converts back. Writing a function named operator| teaches | about your type; Operators and comparisons covers this in depth.
#include <cstdint>
#include <print>
#include <utility>
enum class Perm : std::uint8_t { none = 0, read = 1, write = 2, run = 4 };
Perm operator|(Perm a, Perm b) {
return static_cast<Perm>(std::to_underlying(a) | std::to_underlying(b));
}
bool has(Perm set, Perm flag) {
return (std::to_underlying(set) & std::to_underlying(flag)) != 0;
}
int main() {
Perm perms = Perm::read | Perm::write;
std::println("{:03b}", std::to_underlying(perms));
std::println("can write: {}", has(perms, Perm::write));
std::println("can run: {}", has(perms, Perm::run));
}Output
011 can write: true can run: false
perms holds 3, which has no name in Perm. That’s fine: an enum with a fixed underlying type can hold any value of that type.
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
enum class | Any fixed list of choices: bases, levels, states, modes. | Its values can’t be mixed with numbers or other enums, and -Wswitch finds missing cases. | enum class Level { debug, info }; |
enum class with a small type | You store many values: a genome’s bases, a pixel’s class. | Each value takes 1 byte instead of 4. | enum class Base : std::uint8_t { A, C, G, T }; |
enum class as flags | Several yes/no settings that travel together. | One small integer holds them all, with a name for each bit. | Values 1, 2, 4, …, plus operator| and a has function. |
Plain enum | Reading older code and system headers that use them. | You’ll meet them, but new code gains nothing from them. | enum Base { A, C, G, T }; |
Rule of thumb: write enum class, switch over it without a default, and convert to a number only with std::to_underlying.
Under the hood
An enum value is its number and nothing more. The names are for you and the compiler; the program only stores the integer. So an array of enum values is an array of integers, and the underlying type decides its size:
#include <array>
#include <cstdint>
#include <print>
enum class Base : std::uint8_t { A, C, G, T };
enum class WideBase { A, C, G, T };
int main() {
std::array<Base, 4> small = {Base::G, Base::A, Base::T, Base::C};
std::array<WideBase, 4> wide = {WideBase::G, WideBase::A, WideBase::T,
WideBase::C};
std::println("{} {}", sizeof(small), sizeof(wide));
}Output
4 16
| Value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | Size |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
std::array<Base, 4> | G=21 byte | A=01 byte | T=31 byte | C=11 byte | 4 bytes | ||||||||||||
std::array<WideBase, 4> | G=24 bytes | A=04 bytes | T=34 bytes | C=14 bytes | 16 bytes | ||||||||||||
With std::uint8_t as the underlying type, the four bases G, A, T and C take one byte each, 4 bytes in all. With the default int, each base takes 4 bytes, 16 bytes in all.
Because an enum is an integer, comparing or copying one costs the same as an int, and a switch over it can become a jump table: the compiler can use the value as an index into a table of code addresses instead of testing each case in turn. The type checks all happen while compiling; none of them cost anything when the program runs.
PerformanceTwo bits would do
A base needs only 2 bits, so even 1 byte wastes three quarters of it. When memory matters, pack four bases into each byte, as Operators and bit operations did, and use the enum at the edges, where you read and write single bases. Module 12, C++ for bioinformatics, builds a packed sequence type this way.
Common pitfalls
A default that hides a missing case
Here Base::N was added for unknown bases, but the switch has a default, so -Wswitch says nothing. N falls into default and is counted as a G or C:
#include <print>
enum class Base { A, C, G, T, N };
bool is_strong(Base b) {
switch (b) {
case Base::A:
case Base::T:
return false;
default:
return true;
}
}
int main() {
std::println("{}", is_strong(Base::N));
}Output
true
The fix is to list every case and drop default. Then adding N makes the compiler point at this switch, and you decide what an unknown base means here.
Mixing two plain enums
Plain enums let you compare values of different enum types. Both compilers warn, so with warnings as errors it doesn’t compile; without -Werror, it would compile and compare two unrelated numbers:
enum Base { A, C, G, T };
enum Level { debug, info, warning, error };
int main() {
Base b = G;
if (b == warning) {
b = A;
}
}The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:6:11: error: comparison between ‘enum Base’ and ‘enum Level’ [-Werror=enum-compare]
6 | if (b == warning) {
| ~~^~~~~~~~~~
cc1plus: all warnings being treated as errorsThe fix is to make both of them enum class. Then the comparison is an error in every build, not only a warning.
Casting any number to an enum
static_cast<Base>(code) accepts any int, even one with no name in Base. (For a plain enum without : type, a number outside the range its enumerators need is undefined behavior.) When the number comes from a file or a user, check it before casting:
#include <optional>
#include <print>
enum class Base { A, C, G, T };
std::optional<Base> base_from_code(int code) {
if (code < 0 || code > 3) {
return std::nullopt;
}
return static_cast<Base>(code);
}
int main() {
std::println("{}", base_from_code(2) == Base::G);
std::println("{}", base_from_code(9).has_value());
}Output
true false
Try it yourself
Try it yourself
Add a function complement that returns the base each base pairs with (A with T, C with G), and print the complement of the sequence on a second line.
#include <print>
#include <utility>
#include <vector>
enum class Base { A, C, G, T };
char to_char(Base b) {
return "ACGT"[std::to_underlying(b)]; // A is 0, C is 1, ...
}
int main() {
std::vector<Base> seq = {Base::G, Base::A, Base::T, Base::C};
for (Base b : seq) {
std::print("{}", to_char(b));
}
std::println("");
}Expected output
GATC CTAG
Show a hint
Write Base complement(Base b) with a switch: A gives T, T gives A, C gives G and G gives C. Put a return after the switch, since b could hold a number with no name.
Show a solution
#include <print>
#include <utility>
#include <vector>
enum class Base { A, C, G, T };
char to_char(Base b) {
return "ACGT"[std::to_underlying(b)]; // A is 0, C is 1, ...
}
Base complement(Base b) {
switch (b) {
case Base::A:
return Base::T;
case Base::C:
return Base::G;
case Base::G:
return Base::C;
case Base::T:
return Base::A;
}
return b;
}
int main() {
std::vector<Base> seq = {Base::G, Base::A, Base::T, Base::C};
for (Base b : seq) {
std::print("{}", to_char(b));
}
std::println("");
for (Base b : seq) {
std::print("{}", to_char(complement(b)));
}
std::println("");
}Listing every case without a default means -Wswitch checks that complement handles every base. The return after the switch satisfies GCC; it only runs for a value with no name.
Saved in this browser only.