简体   繁体   中英

Constness in brackets operator in custom container

I have a custom class with two overloaded brackets operators -- setter and getter. As you know they look somewhat like this

class IntContainer {
public:
    int const & operator[] (size_t i) const;
    int & operator[] (size_t i);
}

The problem I'm facing now, is that I have to check when the value was set or when it was just accessed, that is I need to track all the changes in my container. It's hard since always only non const operator is called, for example

container[i] = 3;  // Non const operator[] called
x = container[i];  // Again, non const operator[] called

In two cases above I need to differ inner behavior in container. So is there any way to explicitly call different operators in cases like above. I don't want to use const instance of container and to define another functions like set and get , though I'm looking for smoe right design pattern.

Thanks!

One trick is to create a proxy object. This lets you overload the assignment operator and put your tracking logic into there and then you can guarantee that any writes are captured. If you have

class Proxy
{
    int& val;
    Proxy(int& val) : val(val) {}
    Proxy& operator=(int new_val)
    {
        // do tracking stuff
        val = new_val;
    }
    operator int() { return val; }
};

then you can adjust IntContainer to

class IntContainer {
public:
    int operator[] (size_t i) const;
    Proxy operator[] (size_t i);
};

and now you'll call the tracking code when the user actually tries to assign into the reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM