C++20 Concepts Applied – Safe Bitmasks Using Scoped Enums -- Andreas Fertig

logo.pngIt can be hard to follow code using enable_if. Andreas Fertig gives a practical example where C++20’s concepts can be used instead.

C++20 Concepts Applied – Safe Bitmasks Using Scoped Enums

by Andreas Fertig

From the article:

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 providing an operator, a function template that only gets enabled if you opt-in for a desired enum. Listing 1 is the implementation, including the definition of Permission.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.