Overloading the C++ indexing subscript operator [] in a manner that allows for responses to updates -


consider task of writing indexable class automatically synchronizes state external data-store (e.g. file). in order class need made aware of changes indexed value might occur. unfortunately usual approach overloading operator[] not allow this, example...

type& operator[](int index) {     assert(index >=0 && index < size);     return state[index]; } 

i there way distinguish between value being accessed , value being modified?

type = myindexable[2]; //access myindexable[3] = a;  //modification 

both of these cases occur after function has returned. there other approach overloading operator[] perhaps make more sense?

from operator[] can tell access.
if external entity uses non cost version not mean write take place rather take place.

as such need return object can detect modification.
best way wrap object class overrides operator=. wrapper can inform store when object has been updated. want override operator type (cast) const version of object can retrieved read accesses.

then this:

class writecheck; class store {   public:   type const& operator[](int index) const   {     return state[index];   }    writecheck operator[](int index);   void stateupdate(int index)   {         // called when particular index has been updated.   }   // stuff };  class writecheck {      store&  store;     type&   object;     int     index;      public: writecheck(store& s, type& o, int i): store(s), object(o), index(i) {}      // when assignment done assign     // inform store.     writecheck& operator=(type const& rhs)     {         object = rhs;         store.stateupdate(index);     }      // still allow base object read     // within wrapper.     operator type const&()     {         return object;     }    };        writecheck store::operator[](int index) {        return writecheck(*this, state[index], index); } 

an simpler alternative is:
rather provide operator[] provide specific set method on store object , provide read access through operator[]


Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - jQuery UI Splitter/Resizable for unlimited amount of columns -

javascript - IE9 error '$'is not defined -