Single assignment for basic types in C++
<p>I'd like to create a "single assignment" wrapper for basic types (such as int) that talks like an int, walks like an int, smells like an int, but can only be modified or assigned to at most once (like in some pure functional languages). For example (copy constructor omitted to keep the example simple):</p>

<pre><code>template&lt;class T&gt;
struct SA {
    SA&lt;T&gt;(T init) : wasAssigned(false) {
        val = tmp = init;
    }
    SA&lt;T&gt; &amp; operator=(const T&amp; other) {
        if (!wasAssigned) {
            if (val != tmp) {
                val = tmp;
            } else {
                val = tmp = other;
            }
            wasAssigned = true;
        }
        return *this;
    }
    operator T&amp; () {
        if (!wasAssigned &amp;&amp; (val != tmp)) {
            wasAssigned = true;
            val = tmp;
        } else {
            tmp = val;
        }
        return tmp;
    }
private:
    bool wasAssigned;
    T val, tmp;
};
</code></pre>

<p>This is close, but not perfect. It relies on the val/tmp equality test to detect changes, and fails in this case:</p>

<pre><code>SA&lt;int&gt; i(3);
cin &gt;&gt; i;
i = 5;
</code></pre>

<p>Iff the <code>cin &gt;&gt; i</code> assigns the same value as the initial value (3), i will be 5 at the end. How can this be fixed?</p>
