Why You Should Use Class Enums in C++
This post was originally published on Admiral Ackbar’s Code Emporium .
This is a brief post about what class enums are in C++, and why you should use them.
The Problem: Enums Pollute Global Scope
Here’s a conflict you might get when using enums:
Old School Solutions
Here are two solutions for the above conflict:
The above works, but it is messy, and requires you to be dilligent in naming your values consistently. Here’s a solution with a cleaner result:
The result above is much cleaner, but the syntax to define it is a little clunky.
The C++11 Solution: Class Enums
This is why C++11 defined the class enum. Here’s how to use it:
Here we get the same clean access, and the syntax to define the enums is nice and clean as well. That’s why you should be using class enums wherever you’ve been using enums in the past!
Comments