title: Is there any existing solution to make portable ordered bit fields?
body: <p>I'd like to have a way to specify bitmaps, which would look like this:</p>
  
  <pre><code>struct Bitmap
  {
      unsigned foo: 2;
      unsigned bar: 5;
      unsigned baz: 3;
  };
  </code></pre>
  
  <p>, and many similar structures, but I need the bit fields to have predictable order. But C++ doesn't guarantee any order or packing of bit fields, so I have to make some special code to implement this using bitwise operations. This could be implemented for the above structure as follows:</p>
  
  <pre><code>class Bitmap
  {
      unsigned value;
  public:
      unsigned foo() { return value&amp;0x3; }
      unsigned bar() { return (value&gt;&gt;2)&amp;0x1f; }
      unsigned baz() { return (value&gt;&gt;7)&amp;0x7; }
      void set_foo(unsigned new_foo) { value=(value&amp;~0x3)|new_foo; }
      void set_bar(unsigned new_bar) { value=(value&amp;~(0x1f&lt;&lt;2))|(new_bar&lt;&lt;2); }
      void set_baz(unsigned new_baz) { value=(value&amp;~(0x7&lt;&lt;7))|new_baz; }
      Bitmap(unsigned newFoo,unsigned newBar,unsigned newBaz)
          : value(newFoo|(newBar&lt;&lt;2)|(newBaz&lt;&lt;7))
      {}
  };
  </code></pre>
  
  <p>Writing such code for many different bitmaps is a repeating task, which is why I'd like to automate it. I might use templates for this, but in that case I won't be able to name my bit fields differently for each structure (or will have to write even more code to wrap generic structure to provide the names).</p>
  
  <p>Ideally I'd to have some macro to use similarly to this:</p>
  
  <pre><code>DEFINE_BITMAP(Bitmap,foo,2,bar,5,baz,3);
  Bitmap myBits(1,9,5);
  doStuff(myBits.bar());
  </code></pre>
  
  <p>where number of fields can differ between invocations of <code>DEFINE_BITMAP</code>, as can the widths.</p>
  
  <p>So before I start inventing this wheel: has it already been done? If yes, what to look for?</p>