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);
constlong& operator[](const string& key) const;
void SetField(const string& key, constlong& 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"]
#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:
operatorlong () 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 } ;
}
};
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)
?