// READWRIT.CPP -- distinguishing between reads and writes #include template class proxy { // proxy is a type created just to cause conversions so // client code can distinguish between reads and writes. // Note that all conversion operations are defined in this // class. public: // promotion constructor - used when saving a pointer to object proxy(T *tptr) { cout << "saving ptr -- "; data = tptr; } // assignment - used when writing a T to a proxy void operator=(const T &t) { cout << "writing value = " << t; *data = t; } // cast operator - used when reading a T from a proxy operator const T() { cout << "reading value = " << *data; return *data; } private: T *data; // a pointer back to original object }; template class array { public: array(int size=10) { _data = new T[_size=size]; } int size() { return _size; } // note that operator[] returns a proxy proxy operator[](int n) { return (_data+n); } private: T *_data; int _size; }; void msg(char* s) { cout << s; }; void main() { cout << "\n\ntesting reads and writes\n"; msg("\nstatement #1: "); array test1(5); msg("\nstatement #2: "); test1[0] = 4; msg("\nstatement #3: "); int xi = test1[0]; cout << endl; msg("\nstatement #4: "); array test2(5); msg("\nstatement #5: "); test2[0] = 4.55; msg("\nstatement #6: "); double xd = test2[0]; cout << endl; }