title: Mask from bitfield in C++
body: <p>Here's a little puzzle I couldn't find a good answer for:</p>
  <p>Given a struct with bitfields, such as</p>
  <pre class="lang-cpp prettyprint-override"><code>struct A {
      unsigned foo:13;
      unsigned bar:19;
  };
  </code></pre>
  <p>Is there a (portable) way in C++ to get the correct mask for one of the bitfields, preferably as a compile-time constant function or template?</p>
  <p>Something like this:</p>
  <pre class="lang-cpp prettyprint-override"><code>constinit unsigned mask = getmask&lt;A::bar&gt;();  // mask should be 0xFFFFE000
  </code></pre>
  <p>In theory, at runtime, I could crudely do:</p>
  <pre class="lang-cpp prettyprint-override"><code>unsigned getmask_bar() {
      union AA {
          unsigned mask;
          A fields;
      } aa{};
      aa.fields.bar -= 1;
      return aa.mask;
  }
  </code></pre>
  <p>That could even be wrapped in a macro (yuck!) to make it &quot;generic&quot;.</p>
  <p>But I guess you can readily see the various deficiencies of this method.</p>
  <p>Is there a nicer, generic C++ way of doing it? Or even a not-so-nice way? Is there something useful coming up for the next C++ standard(s)? Reflection?</p>
  <p>Edit: Let me add that I am trying to find a way of making bitfield manipulation more flexible, so that it is up to the programmer to modify multiple fields at the same time using masking. I am after terse notation, so that things can be expressed concisely without lots of boilerplate. Think working with hardware registers in I/O drivers as a use case.</p>