Gabriel.vs
Gabriel.vs

Reputation: 56

Need to call a function (referenced by static pointer) from a static member

everyone. Recently I face the challenge. Cannot say that it was a critical problem, but just an interesting thing. There is src code:

class Data {
typedef void (Object::*CallBack)(void);

public:
Data() : m_callBack(NULL) {}
void setCallBack(CallBack ptr)
{
    m_callBack = ptr;
}
void start()
{
    Aux::someAction();
}

private:
static CallBack m_callBack;

class Aux{
    public:
    static someAction()
    {
        if(m_callBack)
        {
            // How to call function for this reference ? - m_callBack
        }
    }
}; // End of 'Aux' class
}; // End of 'Data' class

So, I know that we can call functions from pointers like that: (this->*m_callBack)(). But static class members do not have an access to ‘this’ pointer. Of course, I can store a pointer of a parent with m_callBack pointer and call (parent->*m_callBack)(). In same cases it may be not so good. So, my question: Is there any other methods to call m_callBack function from a static class member. Also, I’m interesting about – if m_callBack references to class member of static OR non static function.

Upvotes: 0

Views: 90

Answers (2)

Luca Martini
Luca Martini

Reputation: 1474

I think you have a design problem. Either you want to have a non-static Callback (i.e., m_callBack) or you want to typedef your Callback as a static function (i.e. that does not need this).

Upvotes: 0

AndersK
AndersK

Reputation: 36082

You should make the member variable m_callBack public if you want it to work. Then you could write

Data::setCallback(...);

...

Data::m_callBack();

or rather

if ( Data::m_callBack )
{
   Data::m_callBack();
}

Upvotes: 1

Related Questions