47

Shared Enum Operators

 5 years ago
source link: https://www.tuicool.com/articles/hit/zmq2ua7
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

Rvm2InN.png!web

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK