I had a problem with the implementation of my container type map. The idea was to save the keys in the tree, and the values ​​in the file.

using pm1_t = lib::PersistentMap <int,int>; pm1_t myMap(); //999 key , 100 value myMap[999] = 100; 

That is, 999 goes to the avl tree, and then a file is created with the name 999 and the value 100 is stored in it.

The question is how to catch the equating operator in order to write the value to a file.

PS

For example, I have such a code.

 class fixed_array { public: typedef int size_type; fixed_array(size_type size) : size_(size) { data_ = new T[size_]; } size_type size() const { return size_; } T& operator[](size_type index) { //assert(index < size_); return data_[index]; } const T& operator[](size_type index) const { assert(index < size_); return data_[index]; } private: T* data_; size_type size_; }; void main() { using pm1_t = fixed_array <int, int>; pm1_t myMap(3); //хотелось как перехватить тут оператор приравнивания myMap[1] = 100; } 

I can not understand how to intercept the value of 100, and save it to a file immediately.

  • Uh, if you have implemented the container yourself, then the question of overloading the assignment should not be. - VladD

1 answer 1

The [] operator must return an object of a special class (shim), in which the assignment operator will already be redefined. See, for example, the implementation of std :: vetctor.

 template<typename T1, typename T2> struct PersistentMap; template<typename T1, typename T2> struct PersistentMapProxy { PersistentMap<T1, T2> & parent; T1 key; PersistentMapProxy( PersistentMap<T1, T2> & parent, T1 key ) : parent(parent) , key(key) {} const T2& operator = ( const T2& value ) const { parent.assign( key, value ); return value; } operator const T2& () const { return parent.get( key ); } }; template<typename T1, typename T2> struct PersistentMap { .... typedef PersistentMapProxy<T1, T2> Proxy; Proxy operator[] ( T1 key ) { return Proxy(*this, key); } void assign( T1 key, const T2& value ){ .... } ... }; 
  • If possible, an example of using this structure would not hurt. - Demolver
  • Thanks a lot, I now understand the design. - Demolver
  • I have a question, but what if I want to send myMap [1] to some method, for example inc (myMap [1]), where Inc. is void inc (int & a). The compiler swears on not joining types & int and proxy - Demolver
  • No The cast to int & is the provision of a path for the subsequent modification of a variable, in fact by a pointer to it, i.e. without calling an additional function. This is what you wanted to avoid. - Chorkov
  • I understood everything ... it was a building trap ... myMap [2] = 20; int c = 30; modify (c); modify (myMap [2]); myMap [2] = myMap [2] + 20; assert (myMap [2] == 45); Thank you very much. - Demolver