C++20 Concepts Applied -- Andreas Fertig
In this post, we'll dive into implementing this technique in C++17 and then explore how it evolves with the application of C++20 concepts to the code. The goal is to simplify the code by eliminating the need for cumbersome constructs like enable_if and introduce further improvements in C++23.
C++20 Concepts Applied - Safe Bitmasks using Scoped Enums
by Andreas Fertig
From the article:
In 2020 I wrote an article for the German magazine iX called Scoped enums in C++. In that article, I shared an approach of using class enums as bitfields without the hassel of having to define the operators for each enum. The approach was inspired by Anthony William's post Using Enum Classes as Bitfields.
Today's post aims to bring you up to speed with the implementation in C++17 and then see how it transforms when you apply C++20 concepts to the code.
One operator for all binary operations of a kind
The idea is that the bit-operators are often used with enums to create bitmasks. Filesystem permissions are one example. Essentially you want to be able to write type-safe code like this:
using Filesystem::Permission; Permission readAndWrite{Permission::Read | Permission::Write};
The
enum Permission
is a class enum, making the code type-safe. Now, all of you who once have dealt with class enums know that they come without support for operators. Which also is their strength. You can define the desired operator or operators for each enum. The issue here is that most of the code is the same. Cast the enum to the underlying type, apply the binary operation, and cast the result back to the enum type. Nothing terribly hard, but it is so annoying to repeatedly type it.Anthony solved this by...