title: Using an already-defined struct as an anonymous member of a union
body: <p>Let's say I have a 32-bit hardware register <code>Reg</code> that I want to be able to access either as a 32-bit value (e.g. <code>Reg = 0x12345678</code>) or as bitfields (e.g. <code>Reg.lsw = 0xABCD</code>). I can achieve this by declaring a union with anonymous struct member, and declaring assignment and conversion operators to/from <code>uint32_t</code>. In a little-endian environment, the code might look like this:</p>
  
  <pre><code>#include &lt;cstdint&gt;
  #include &lt;cstdio&gt;
  
  typedef union
    {
    uint32_t val ;
    struct
      {
      uint32_t lsw : 16 ;
      uint32_t msw : 16 ;
      } ;
  
    operator = (uint32_t n) { val = n ; }
    operator uint32_t() const { return val ; }
    } HWR ;
  
  int main()
    {
    HWR Reg ;
    Reg = 0x12345678 ;
    Reg.lsw = 0xABCD ;
    printf ("%X\n", uint32_t(Reg)) ;
    }
  </code></pre>
  
  <p>But now let's say I have a whole bunch of these registers, each with its own bitfield layout, and I have a header file <code>FieldDefs.h</code> that declares these bitfield layouts as named structures. How can I use these named structures in the above code, so that I can access the 32-bit value and also the individual bitfields? I could do it like this:</p>
  
  <pre><code>#include "FieldDefs.h" // Defines struct MyHWR
  typedef union
    {
    uint32_t val ;
    struct MyHWR field ;
  
    operator = (uint32_t n) { val = n ; }
    operator uint32_t() const { return val ; }
    } MyHWRUnion ;
  </code></pre>
  
  <p>But now instead of <code>Reg.lsw =...</code>, I need to type <code>Reg.field.lsw =...</code></p>
  
  <p>Is there any way (in C++17) to declare an already defined struct as an anonymous member of a union? I am using g++ version 7.3.0 if it matters.</p>