title: Variable-sized bitfields with aliasing
body: <p>I have some struct containig a bitfield, which may vary in size. Example:</p>
  
  <pre><code>struct BitfieldSmallBase {
      uint8_t a:2;
      uint8_t b:3;
      ....
  }
  
  struct BitfieldLargeBase {
      uint8_t a:4;
      uint8_t b:5;
      ....
  }
  </code></pre>
  
  <p>and a <strong>union</strong> to access all bits at once:</p>
  
  <pre><code>template&lt;typename T&gt;
  union Bitfield 
  {
      T bits;
      uint8_t all;    // &lt;-------------  Here is the problem
  
      bool operator &amp; (Bitfield&lt;T&gt; x) const {
          return !!(all &amp; x.all);
      }
      Bitfield&lt;T&gt; operator + (Bitfield&lt;T&gt; x) const {
          Bitfield&lt;T&gt; temp;
          temp.all = all + x.all;   //works, because I can assume no overflow will happen
          return temp;
      }
      ....
  }
  
  typedef Bitfield&lt;BitfieldSmallBase&gt; BitfieldSmall;
  typedef Bitfield&lt;BitfieldLargeBase&gt; BitfieldLarge;
  </code></pre>
  
  <p>The problem is: For some bitfield base classes, an uint8_t is not sufficient. BitfieldSmall does fit into a uint8_t, but BitfieldLarge does not. The data needs to be packed as tightly as possible (it will be handled by SSE instructions later), so always using uint16_t is out of question. Is there a way to declare the "all" field with an integral type, whose size is the same as the bitfield? Or another way to access bits as a whole?</p>
  
  <p>I can of course forego the use of the template and declare every kind of bitfield explicitly, but I would like to avoid code repetition (there is quite a list of operators und member functions).</p>