Traditional C++ enum
had several issues. To solve these problems, C++11 introduced a new feature called enum class
. In this article, I will examine the problems with the traditional enum
and how they are solved with enum class
.
First, traditional enum
could not be forward-declared. The reason was that if the values in the enumerator were unknown, it was impossible to determine their size. However, enum class
is treated as int
if an underlying type is not specified, assigning values outside the range of an int
will raise a compilation error. If you want to use values outside the range of an int
, you need to specify the underlying type.
Another problem with traditional enum
was that the scope of enumerator names was not limited. Let's see the following example.
Here, we try to represent the results of IO
and Parse
functions with enum
s. However, this code will not compile because the Error
and Ok
of IOResult
conflict with those of ParseResult
. To resolve this issue, you can change the enumerator names, or use namespace
s.
However, with enum class
, the names of enumerators are limited to the scope of the enum class
, so there is no need for such verbose code.
Most importantly, the biggest problem with traditional enum
was that they were weakly typed and could be implicitly converted to integer types. However, enum class
do not allow implicit conversion to integer types. If you try to use an enum class
as an int
, you will encounter a compilation error. You need to use static_cast
to explicitly cast it.
As explained above, traditional enum
cannot be forward-declared, their enumerator names are not limited in scope, and they can be implicitly converted to integer types. For now, enum class
are the correct approach in most case.
Note: This article is a translation of a Korean post written in 2015. If you want to read the original, please refer to this link.
Comments
Post a Comment