Shared Enum Operators – Hacker Noon

C++ Telltales part 2:

This is second part of my C++ Telltales series where I share some tips and tricks to work with C++. Feel free to check out also other parts of the series from my profile!

C++ enums are useful when you have to create a type that can be used as a flag. To use them as flags, they need to have operators to compare if specific flag is set or to provide a combination of enumeration values. To prevent extra work (or if you are just feeling plain lazy), you can introduce shared operators for all enums by utilizing templates. Here is a small snippet how to do that:

What’s great about this solution is that it only works for enumerations due to std::enable_if type trait and only for enumerations in the same namespace. To utilize it to the maximum, just keep your flag enumerations in same namespace and remember to include the header file you have the templates declared.

And here is the same image from my previous part to get some cover photo for this article (I am feeling lazy..):

read original article here