Operator[] C++ Get/Set -
i'm having trouble telling difference between , set operator[]. need tell difference between these function calls.
cout << data[5]; data[5] = 1;
i googled it, , answers found still didn't help. people suggested making signatures methods different adding const. did that, , still both called same method.
there signatures had used:
const t& operator[](unsigned int index) const; t& operator[](unsigned int index);
what doing wrong?
the solution use "proxy" object delay actual operation:
#include <vector> #include <iostream> template<typename t> struct myarray { std::vector<t> data; myarray(int size) : data(size) {} struct deref { myarray& a; int index; deref(myarray& a, int index) : a(a), index(index) {} operator t() { std::cout << "reading\n"; return a.data[index]; } t& operator=(const t& other) { std::cout << "writing\n"; return a.data[index] = other; } }; deref operator[](int index) { return deref(*this, index); } }; int main(int argc, const char *argv[]) { myarray<int> foo(3); foo[1] = 42; std::cout << "value " << foo[1] << "\n"; return 0; }
simple const
-ness cannot used because may need read non-const instance, reason must delay operation: assignment happens "after" access , compiler doesn't tell if access later used target assignment or not.
the idea therefore on access store away index has been requested , wait know if reading or writing operation happening. providing implicit conversion operator proxy t
know when reading operation occurs, providing , assignment operator proxy t
know when writing occurs.
Comments
Post a Comment