Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++ can I reset the function pointer for an operator?

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]; };
};
like image 753
Michael Fitzpatrick Avatar asked Jul 03 '26 08:07

Michael Fitzpatrick


2 Answers

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.

like image 96
Oliver Charlesworth Avatar answered Jul 05 '26 00:07

Oliver Charlesworth


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 );
like image 30
eugene_che Avatar answered Jul 05 '26 01:07

eugene_che



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!