vendredi 14 février 2020

Overload -> arrow operator in shared_ptr

I'm trying to overload the -> operator to eventually execute something along the lines:

MyInterface *myInstance = (MyInterface *)(new A());
myInstance->Toggle(); //this works wonderfully

std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(pIOnAcess);

//the next line doesn't compile, I would like to achieve something like this, but even 
//sharedPtrWrapper.get()->Toggle(); 
//would be nice to achieve, is this possible? 
sharedPtrWrapper->Toggle(); 

//this works:
sharedPtrWrapper->operator->()->Toggle();

Note: I have no control over MyInterface, cannot implement the pure virtual destructor.

Here is what I tried (the below code runs):

#import <memory>
#import <iostream>

struct MyInterface {
    virtual bool Toggle() = 0;
};

class A : public MyInterface {
public:
    bool Toggle() {
        stateEnabled = !stateEnabled;
        std::cout<<"current state " << stateEnabled << std::endl;
        return true;
    }
private:
    bool stateEnabled = false;
};

template <typename T>
class Wrapper {
private:
    T *unsafePointer = nullptr;
public:
    Wrapper<T>()
    { }

    T *operator->() const {
        return unsafePointer;
    }

    Wrapper<T>(T *stuff) {
        unsafePointer = stuff;
    }

    ~Wrapper<T>() {}
};

int main(int argc, const char * argv[]) {
    MyInterface *myInstance = (MyInterface *)(new A());
    myInstance->Toggle();


    Wrapper<MyInterface> wrapperS(myInstance);
    wrapperS->Toggle();


    std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(myInstance);
    sharedPtrWrapper->operator->()->Toggle();
    sharedPtrWrapper.operator->()->operator->()->Toggle();

    sharedPtrWrapper.get()->operator->()->Toggle();

    (*sharedPtrWrapper).operator->()->Toggle();

    return 0;
}

Output:

current state 1
current state 0
current state 1
current state 0
current state 1
current state 0
Program ended with exit code: 0

Note: stackoverflow doesn't let me post this question, because my post has more code than text.

Aucun commentaire:

Enregistrer un commentaire