Unions in c++ and bitwise operations
<p>I have seen the following structure in a source code.</p>

<pre><code>template&lt;unsigned bitno, unsigned nbits = 1, typename T = u8&gt;
struct RegBit
{
    T data;
    enum { mask = (1u &lt;&lt; nbits) - 1u };
    template&lt;typename T2&gt;
    RegBit&amp; operator=(T2 val)
    {
        data = (data &amp; ~(mask &lt;&lt; bitno)) | ((nbits &gt; 1 ? val &amp; mask : !!val) &lt;&lt; bitno);
        return *this;
    }
    operator unsigned() const { return (data &gt;&gt; bitno) &amp; mask; }
};

union {
    u8 raw;
    RegBit&lt;0&gt; r0;
    RegBit&lt;1&gt; r1;
    RegBit&lt;2&gt; r2;
    RegBit&lt;3&gt; r3;
    RegBit&lt;6&gt; r6;
    RegBit&lt;7&gt; r7;
} P;
</code></pre>

<p>After a first reading, I found out that an <code>unsigned</code> cast of an object whose type is <code>RegBit</code> will return the bit number <code>bitno + 1</code> of <code>data</code>.</p>

<p>However, I don't understand how the <code>=</code> overloaded operator is handled. I mean that I understand the syntax, but not what the bitwise operation is meant to do.</p>

<p>And last thing, if you run the code and affect a value to <code>P.raw</code>, you'll notice that <em>∀ i ∈ [0;7], <code>P.ri.data = P.raw</code></em>. </p>

<p>How is that possible ?
Of course then, the code does what it's suppose to do imho, ie: <em>∀ i ∈ [0;7], <code>(unsigned)P.ri</code> is the (i+1)th bit of <code>P.raw</code>.</em> </p>