c++11 - C++ operator [] -
i trying implement operator [] used once set , once get, need differentiate between 2 cases, in case of get, need throw exception if returned value equal -1; whereas in case of set overwrite value. appple[2] = x; y=apple[2];
i dont know how differentiate between 2 modes, function signature is:
double& security::operator[](quartertype index){ if(index<0 || index>max_quaters){ throw listexceptions::quarteroutofbound(); } return evaluation[index].getvalueaddress(); }
c++ not allow distinction of
appple[2] = x; y=apple[2]; the common solution return proxy object:
struct appleproxy { security & obj; unsigned index; appleproxy(security &, unsigned) : ... {} operator double() // getter { return obj.getat(index); } operator=(double rhs) { obj.setat(index, rhs); } } appleproxy operator[](unsigned index) { return appleproxy(*this, index); } proxy require significant attention detail, i've omitted const correctness, life-time management, taking-the-address-of (double & x = apple[2]; x = 17;), etc.
due pitfalls, tend avoid them.
Comments
Post a Comment