From: Andrey Semashev (andrey.semashev_at_[hidden])
Date: 2025-06-10 23:34:29


Hi,

There were quite a few times when I wanted to use bitwise operations on
atomic<enum>, where the enum lists a number of flags that could be
combined with bitwise AND, OR and XOR. Neither std::atomic nor
Boost.Atomic enables bitwise operations for enums, so I had to resort to
workarounds, such as using atomic<underlying_type_t<enum>> with explicit
casts to and from the underlying type of the enum. Obviously, this is
rather tedious, and I would prefer not to have to do this.

I'm not sure what was the original rationale for not allowing bitwise
operations for std::atomic<enum>, but I would guess these points were a
part of it:

1. Not all enums represent bit masks, so for some enums the bitwise
operations wouldn't make sense.
2. There may be user-defined bitwise operators defined for an enum, and
presumably atomic<enum> would not invoke them to implement atomic
bitwise operations. (Because it is generally not possible to make an
arbitrary user's operator implementation atomic, other than to wrap it
in a CAS loop, which defeats the point of having a dedicated atomic
operation.) Some users may find this surprising.
3. For some operations, there may be multiple reasonable
implementations. For example, bitwise complement (operator~) may be
inverting all bits in the enum representation or only those bits, for
which there are named values. An atomic<enum> could possibly implement
the former, but the user's operator~ could implement the latter, which
would introduce a discrepancy in behavior.

Also, ironically, if atomic<enum> attempted to solve the problem #1 by
detecting presence of user-defined bitwise operators for the enum and
took it as a sign that the enum is a bit mask, this would only emphasize
the problems #2 and #3.

So, clearly, on one hand the functionality could be useful in practice,
and on the other hand there may be pitfalls and confusion coming from
it. I wonder what people think about this. Would you prefer to have the
support and deal with the consequences or the status quo? Perhaps, you
had your own solutions to this problem? Maybe there are other strong
reasons to not have it?

Personally, I'm leaning towards having the functionality rather than
not. You can always not use what you don't want or need, but not the
other way around.

Thanks.