Hackernoon logoShared Enum Operators by@drodil

Shared Enum Operators

Author profile picture

@drodilHeikki Hellgren


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 here!

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..):

If you liked the story, please press the ❤ button below (did you know that you can give more than one clap). Also please feel free to share this story!

About me

I am Heikki Hellgren, Software Expert and technology enthusiast working at Elektrobit Automotive. My interests are in software construction, tools, automatic testing and all the new and cool stuff like AI and autonomous driving. You can follow me on Medium and Twitter and check out my websitefor more information.


The Noonification banner

Subscribe to get your daily round-up of top tech stories!