operator[]: distinguish read and write

Hi,

I wonder if it is possible to write, for some class, an operator[] which distinguishes between read and write access, to keep track of properties of the data content of an object.

1
2
3
4
5
6
7
class Test {
    T x[10];
    bool some_property;
public:
    const T & operator[] (int i) const { return x[i]; }
    T & operator[] (int i) { some_property = false; return x[i]; }
};


This code is setting some_property to false on any read or write access to a non-const object. But this should be done only on write.

I could write Test::set() and Test::get(), but it's of course nicer to let the operator[] handle it properly. Is this possible?
Yes, there' an example in the ARM. I can't remember if off hand.
Wrap in a helper class and intercept the assignment. Something like:

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
34
35
36
37
38
39
40
41
#include <iostream>

class test
{
    int x[10] = {0} ;
    bool modified = {false}  ;

    class wrapper
    {
        wrapper( test& t, int p ) : object(t), pos(p) {}
        test& object ;
        std::size_t pos ;

        public:
            operator int() const { return object.x[pos] ; }
            wrapper& operator= ( int v )
            {
                if( v != object.x[pos] )
                {
                    object.x[pos] = v ;
                    object.modified = true ;
                    std::cout << "modified set to true\n" ;
                }
                return *this ;
            }

        friend class test ;
    };
    friend class wrapper ;

    public:
        const int& operator[] ( std::size_t i ) const { return x[i]; }
        wrapper operator[] ( std::size_t i ) { return wrapper( *this, i ) ; }
};

int main()
{
    test t ;
    std::cout << "a. " << t[5] << '\n' ;
    std::cout << "b. " << ( t[5] = 6 ) << '\n' ;
}
Thanks! This might help me.
Topic archived. No new replies allowed.