C++ Enum Pattern
Introduction Very often we want to define a set of items to choose from, for example, a set of colors. In C++, we usually can declare enum class Color { Red, Green, Blue }. However, besides using it in a switch statement, we can hardly use it for anything else. For example, if we want to print "Red" for Color::Red, we have to write another function using switch statement, somewhere else. When we want to add a new color, we have to change every places we are using switch. This is obviously an anti-pattern. Occasionally, we want to find how many colors in total, and maybe even want to iterate through them. None of these are supported by C++ enum. In this blog, I want to introduce the Enum Pattern in C++, which supports switch and constains encapsulated member functions, similar to the Enum Class in Java. The idea came from this stackoverflow post.