RFC: BitMask helper ADT

Aaron Ballman aaron at aaronballman.com
Wed Jun 24 06:01:34 PDT 2015


On Tue, Jun 23, 2015 at 7:12 PM, Saleem Abdulrasool
<compnerd at compnerd.org> wrote:
> Hello,
>
> While looking at something unrelated (yay yak-shaving!) ... it came up that
> it may be convenient to actually re-use enumerations as bit masks in certain
> cases (assuming that the values are appropriately disjoint).
>
> The thing is that enum classes are becoming more prevalent, and they are not
> simply usable in logical operations without casting.  The "solution" to this
> is replicate the enumeration.  The helper helps avoid the extensive casting
> by wrapping up the underlying type into a helper that simply provides the
> overloads for the normal (logical) operations.  It would also allow the
> re-use of the enumeration rather than duplicate the values.
>
> The implementation presented here should work with MSVC 2013, clang and GCC.
> It is more of a proof of concept, that this is possible.  This thread is
> meant to raise the question of: is this a good idea?  Do we want to just use
> unsigned for bit masks instead?

While unsigned works for bitmasks, I personally find it to be an
unclear API because there's nothing tying the parameter type to the
bitmask values. Allowing easier use of a strongly-typed bitmask seems
like it's a good design choice, to me. Since I had a hand in the
design of this, I am a bit biased, but I do think that it is useful
functionality. If others have ideas on how to better expose the
functionality, I am not strongly tied specifically to the proposed
approach, but do really like the idea of being able to use scoped
enumerations for bitmasks due to the type safety they provide (which
this solution allows).

Either way, I think the use of bitmasks is common enough in the
codebase to warrant some sort of "official" guidance that we could
codify in the coding standards so that they're used consistently.

~Aaron

> (A thank you goes out to Aaron for a discussion on this idea and help with
> some of the nastier pieces of the metaprogramming here).
>
> One point that I know will most definitely be brought up: the implicit
> boolean conversion.  Yes, its implicit, and yes that was an explicit choice.
> The problem is that the use of logical operators as conditions is pretty
> extensive, so this conversion operator tends to be involved quite often, and
> would be needed to keep the idiomatic use in place.
>
> --
> Saleem Abdulrasool
> compnerd (at) compnerd (dot) org



More information about the llvm-commits mailing list