Preface
In C++11, the strongly typed enum class
type (also known as enumeration class) was introduced. However, there is an awkward issue that std::cout
, the standard stream, does not support outputting enum class
types.
For example, in the following code:
|
|
During compilation, an error will occur. The GCC compilation error message is:
|
|
MSVC compilation error message:
|
|
So, how can we print enum class
?
Solutions
Method One
The underlying type of enum class
is actually the int type, so we can simply cast it directly:
|
|
Method Two
Casting every time is too troublesome, is there a more convenient way? Of course! You can overload the operator<<
operator to achieve this:
|
|
Now you can directly use std::cout
to print without having to cast first.
|
|
Method Three
What if I have multiple enum class
, such as enum Color
, enum Fruit
? Do I have to overload the operator<<
operator once for each? So here we use C++ dark magic SFINAE
to generically support any enumeration class, not limited to a specific one:
|
|
Example:
|
|
Defects
For enumeration classes within a namespace, they cannot be printed, meaning that the following E
cannot be recognized:
|
|
Summary
In C++11, due to the problem that enumeration class (enum class
) cannot be directly output to the std::cout
standard stream, three solutions are provided to solve this issue.
- The first solution is to convert the enumeration class to its underlying int type through a forced type cast, and then output the int value.
- The second solution is to overload the
operator<<
operator to convert the enumeration class to its underlying type before outputting. - The third solution is to use C++’s SFINAE technique to generically support any enumeration class and convert it to its underlying type before outputting.
These solutions can all address the issue of not being able to directly output enumeration classes, providing different choices and flexibility.