In C++ can I reset the function pointer for an operator?
In particular I want to set the member function operator[] to use (or not use) bounds checking. I tried this with no luck:
Is this even possible? If so, Can anyone correct the syntax?
in MyArrayClass.h:
class MyArrayClass {
public:
bool CheckArrayBounds;
float BoundsCheck(int i) {
if (i<_size)
return _data[i];
return TCpx(_INVALID);
}
float NoBoundsCheck(int i) {
return _data[i];
}
void UseBoundsCheck(bool State) {
if (State) {
float (operator[]) = &MyArrayClass::BoundsCheck;
} else {
float (operator[]) = &MyArrayClass::NoBoundsCheck;
}
CheckArrayBounds = State;
}
float operator[](int i) { return _data[i]; };
};
This is not possible. Semantically speaking, member functions are not function pointers (although they may be implemented that way under the hood).
You could perform the check on State inside operator[] (), or use a proxy object.
You cannot change operator for particular object instance in runtime because member functions are stored separately from object attributes and are the same for all object instances. And they are stored in write-protected memory segment. Or could even be inlined by the compiler.
Still you can check for state inside of the operator[] implementation.
Also you can create attribute at and replace operator.
class MyArrayClass {
public:
float (MyArrayClass::*at)(int i);
float BoundsCheck(int i);
float NoBoundsCheck(int i); {
void UseBoundsCheck(bool State) {
at = (State)? &MyArrayClass::BoundsCheck : &MyArrayClass::NoBoundsCheck;
}
};
Usage:
MyArrayClass a;
a.at( 1 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With