tags:

views:

62

answers:

1

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?

+2  A: 

Something like the following might work, although I'm not 100% sure about the side-effects. Basically returning a reference to tmp on all but the first call that gets a non-const reference, plus const methods for read-only access.

operator T& () {
  if (wasAssigned) {
    tmp = val;
    return tmp;
  } else {
    wasAssigned = true;
    return val;
  }
}

operator const T& () const {
  return val;
}

operator T () const {
  return val;
}
casablanca
Where would `tmp` reside?
sbi
`tmp` is the same as it was in the OP's code, a member of the class.
casablanca
Gabriel Burca
casablanca