Duke
Duke

Reputation: 357

Can two pointers to member functions be compared for equality?

I already asked a similar question earlier, but I realise now that it was not specific enough.

What I want to do is find out if two pointers to some member function of a class, combined with an actual object of that class, are equal in the sense that both will "call" (in the sense described below) the same function of the same object. Basically, in this code:

bool isEqual(F* object1, void(F::*_fct1)(), 
             F* object2, void(F::*_fct2)())
{
    TSpecificFunctor<F> specFunc1(object1, fct1);
    TSpecificFunctor<F> specFunc2(object2, fct2);

    return /* Something */;
}

Is there /* Something */ that will return true iff specFunc1 and specFunc2 are pointing to the same member function of the same given object?

There, TSpecificFunctor is defined as follows:

class TFunctor
{
public:
    virtual void call() = 0;
};

template <class TClass> class TSpecificFunctor : public TFunctor
{
public:
    TSpecificFunctor(TClass* _pt2Object, void(TClass::*_fpt)())
    {
        pt2Object = _pt2Object;
        fpt=_fpt; 
    }

    virtual void call() override
    { 
        (*pt2Object.*fpt)();
    }

private:
    void (TClass::*fpt)();
    TClass* pt2Object;
};

In other words, the function should return true iff specFunc1.call() will yield the exact same result as specFunc2.call().

EDIT: For example, this might be an application of what I'm trying to achieve:

class TClassB {
public:
   TClassB() {...}

   void doSomething()
   {
      ...
   }

   void doSomethingElse()
   {
      ...
   }

private:
   /* Some object-specific stuff. */
};

TClassB test;
isEqual(&test, &TClassB::doSomething, &test, &TClassB::doSomething); // ==> true
isEqual(&test, &TClassB::doSomething, &test, &TClassB::doSomethingElse); // ==> false

Upvotes: 3

Views: 138

Answers (1)

lubgr
lubgr

Reputation: 38287

You can compare two pointers to F instances, and you can compare pointer to members. This does the right thing:

bool isEqual(F* object1, void(F::*_fct1)(), 
             F* object2, void(F::*_fct2)())
{
    return object1 == object2 && _fct1 == _fct2;
}

Whether actually calling one or the other in which order yields the same resulting state is another question. If the member functions in question have no side effects, this is the case. But they could also modify global or somehow shared state.

Upvotes: 5

Related Questions