title: Type safe(r) bitflags in C++?
body: <p>While revising some old c++ code, I ran across several <a href="http://en.wikipedia.org/wiki/Bit_field" rel="nofollow noreferrer">bitflags</a> defined as enums.</p>
  
  <pre><code>enum FooFlags
  {
      FooFlag1 = 1 &lt;&lt; 0,
      FooFlag2 = 1 &lt;&lt; 1,
      FooFlag3 = 1 &lt;&lt; 2
      // etc...
  };
  </code></pre>
  
  <p>This isn't uncommon, but it bothered me that as soon as you start to combine flags, you lose the type information.</p>
  
  <pre><code>int flags = FooFlag1 | FooFlag2;   // We've lost the information that this is a set of flags relating to *Foo*
  </code></pre>
  
  <p>Some searching on SO showed that I'm not the <a href="https://stackoverflow.com/questions/1693579/bitflag-enums-in-c">only</a> <a href="https://stackoverflow.com/questions/199606/how-should-c-bitflag-enumerations-be-translated-into-c">one</a> bothered by this.</p>
  
  <p>One alternative is to declare flags as #defines or const integrals, so bitwise operations wouldn't transform the type (probably).  The problem with this is it allows our bit set to commingle with unrelated flags, via ints or other enums.</p>
  
  <p>I'm familiar with <a href="http://www.cplusplus.com/reference/stl/bitset/" rel="nofollow noreferrer">std::bitset</a> and <a href="http://www.boost.org/doc/libs/1_36_0/libs/dynamic_bitset/dynamic_bitset.html" rel="nofollow noreferrer">boost::dynamic_bitset</a>, but neither are designed to address my issue.  What I'm looking for is something like C#'s <a href="http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx" rel="nofollow noreferrer">FlagsAttribute</a>.</p>
  
  <p>My question is, what other solutions are there for a (more) type safe set of bitflags?</p>
  
  <p>I'll post my own solution below.</p>