overloading operator[]

I have a class that acts like map<string, string>. However I want to execute some code when it sets an element. So

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class MyClass {
public:
  long& operator[](const string& key);
  const long& operator[](const string& key) const;

  void SetField(const string& key, const long& value) {
    // do some funny thing with key and value,
    //not necessarily set 'value' within the class.
    //Imagine setting the field on database or attached GUI and forgets about it
  }
  long GetField(const string& key) {
    // do some funny thing with key.  Same as above
  }
};


So basically I can use SetField / GetField to run that code that I want upon updating each field. However with operator[] I don't know how to do so. Can any shred some light on this?

To be precise, I want the following to do the same thing
1
2
myCls.SetField("abc", 123);
myCls["abc"] = 123

and
1
2
long val = myCls.GetField("abc");
long val = myCls["abc"]


Thanks in advance
Something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <string>

struct A
{
    void set_field( std::string key, long data ) { /* update database or create_field */ }
    void create_field( std::string key, long data ) { /* insert into database */ }
    long get_field( std::string key ) const { long v = 0 ; /* read into v from database */ return v ; }

    class field
    {
        A& owner ;
        const std::string key ;
        long value ;

        field( A& owner, std::string key, long data ) : owner(owner), key(key), value(data) {}

        public:
            operator long () const { return owner.get_field(key) ; }
            field& operator= ( long new_value )
            {
                value = new_value ;
                owner.set_field( key, value ) ;
                return *this ;
            }
        friend A ;
    };

    field operator[] ( std::string key )
    {
        long value = get_field(key) ;
        return { *this, key, value } ;
    }
};
Last edited on
Thanks. Would you please explain a bit where line 15 gets called? Also why do we need line 18? Finally, in line 31, do you mean
return field(*this, key, value)
?
> Would you please explain a bit where line 15 gets called?

Line 15 is the constructor. It gets called on line 31 return { *this, key, value } ;


> Also why do we need line 18?

To provide for an implicit conversion to long; to enable long val = object_of_type_A["abc"] ;

object_of_type_A["abc"] returns an object of type A::field which is then implicitly converted to a long


> do you mean return field(*this, key, value)

Yes. http://www.stroustrup.com/C++11FAQ.html#uniform-init
Topic archived. No new replies allowed.