title: Accessing members like array?
body: <p>Due to reading a lot of warnings not to use unions like this:</p>
  
  <pre><code>union rgba
  {
      struct
      {
          uint8_t r, g, b, a;
      } components;
      uint8_t index[4];
      uint32_t value;
  };
  </code></pre>
  
  <p>because this is undefined behavior, I decided to keep things simple like so:</p>
  
  <pre><code>struct rgba
  {
      uint8_t r, g, b, a;
  };
  </code></pre>
  
  <p>but it so happened that sometimes I indeed do need to access <code>r</code>, <code>g</code>, <code>b</code> and <code>a</code> in a loop using indexes, otherwise I have to duplicate pretty long code for each component separately.</p>
  
  <p>So I came up with this:</p>
  
  <pre><code>struct rgba
  {
      u8 r, g, b, a;
  
      constexpr u8&amp; operator[](size_t x)
      {
          return const_cast&lt;u8*&gt;(&amp;r)[x];
      }
  };
  </code></pre>
  
  <p>This relies on the assumption that <code>r</code>, <code>g</code>, <code>b</code> and <code>a</code> are placed in linear fashion in the memory, with no hidden boilerplate in between, and the compiler retains the variable order.</p>
  
  <p>With this, I can access the components just like I wanted:</p>
  
  <pre><code>rgba c;
  for (int i = 0; i &lt; 3; i++)
      c[i] = i ^ (i + 7);
  c.a = 0xFF;
  </code></pre>
  
  <ol>
  <li>Since I made pretty big assumptions, I'm pretty sure that this is even more undefined behavior than using unions for type punning. Am I correct?</li>
  <li>How else can I achieve similar design?
  
  <ol>
  <li>I'd like to avoid writing <code>c.r() = 5</code> if possible since it looks funny.</li>
  <li>Having accessors such as <code>c.components[RED]</code> uses macros, and I like to avoid macros.</li>
  <li>Replacing macros from point 2. with enums will look ugly when one takes into account namespaces needed to access such enum. Imagine <code>c.components[Image::Channels::Red]</code>.</li>
  </ol></li>
  </ol>