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):
template<class T>
struct SA {
SA<T>(T init) : wasAssigned(false) {
val = tmp = init;
}
SA<T> & operator=(const T& other) {
if (!wasAssigned) {
if (val != tmp) {
val = tmp;
} else {
val = tmp = other;
}
wasAssigned = true;
}
return *this;
}
operator T& () {
if (!wasAssigned && (val != tmp)) {
wasAssigned = true;
val = tmp;
} else {
tmp = val;
}
return tmp;
}
private:
bool wasAssigned;
T val, tmp;
};
This is close, but not perfect. It relies on the val/tmp equality test to detect changes, and fails in this case:
SA<int> i(3);
cin >> i;
i = 5;
Iff the cin >> i assigns the same value as the initial value (3), i will be 5 at the end. How can this be fixed?