https://github.com/Dalzhim/ArticleEnumClass-v2
https://github.com/Dalzhim/ArticleEnumClass-v2
Last synced: 17 days ago
JSON representation
- Host: GitHub
- URL: https://github.com/Dalzhim/ArticleEnumClass-v2
- Owner: Dalzhim
- License: bsd-2-clause
- Created: 2017-08-09T07:08:53.000Z (almost 8 years ago)
- Default Branch: master
- Last Pushed: 2017-08-11T13:54:50.000Z (almost 8 years ago)
- Last Synced: 2024-11-14T21:38:01.430Z (6 months ago)
- Language: C++
- Homepage: https://dalzhim.github.io/2017/08/11/Improving-the-enum-class-bitmask/
- Size: 13.7 KB
- Stars: 20
- Watchers: 4
- Forks: 3
- Open Issues: 0
-
Metadata Files:
- Readme: Readme.md
- License: LICENSE
Awesome Lists containing this project
- AwesomeCppGameDev - ArticleEnumClass-v2
README
# Bitmask operators and typesafe comparisons for enum class
*EnumClass.h* is a utility header that allows you to easily generate bitwise operators for your custom `enum class` type like so:
```cpp
enum class myEnum
{
enumerator1 = 0x1 << 0,
enumerator2 = 0x1 << 1,
enumerator3 = 0x1 << 2
};enableEnumClassBitmask(myEnum); // Activate bitmask operators
```
This utility relies on two concepts: enumerators and masks. An enumerator’s purpose is to give a name to a specific bit when it is set. A mask, on the other hand, represents the state of every bit (and this way, of every enumerator), whether they are set or cleared. Comparing an enumerator to a mask using `operator==` or `operator!=` is a compiler error. [A complete blog post](https://dalzhim.github.io/2017/08/11/Improving-the-enum-class-bitmask/) explains why and how this is implemented.Here are some tables that summarize the return type of all of the operators :
#### Binary bitwise operators
| **`E, E`** | **`E`, `bitmask`** | **`bitmask`, `E`** | **`bitmask`, `bitmask`**
| ---------- | --------------------- | --------------------- | ------------------------------
**`operator&`** | `E` | `E` | `E` | `bitmask`
**`operator\|`** | `bitmask` | `bitmask` | `bitmask` | `bitmask`
**`operator^`** | `bitmask` | `bitmask` | `bitmask` | `bitmask`
**`operator&=`** | `bitmask` | `bitmask` | `bitmask` | `bitmask`
**`operator\|=`** | `bitmask` | `bitmask` | `bitmask` | `bitmask`
**`operator^=`** | `bitmask` | `bitmask` | `bitmask` | `bitmask`#### Unary bitwise operators
| **`E`** | **`bitmask`**
| ------- | ----------------
**`operator~`** | `bitmask` | `bitmask`#### Comparison operators
| **`E, E`** | **`E`, `bitmask`** | **`bitmask`, `E`** | **`bitmask`, `bitmask`**
| ---------- | --------------------- | --------------------- | ------------------------------
**`operator==`** | `bool` | `static_assert` | `static_assert` | `bool`
**`operator!=`** | `bool` | `static_assert` | `static_assert` | `bool`