简体   繁体   中英

Get pointer to member function from within member function in C++

Currently in the program I am attempting to write I need to be able to get a pointer to a member function within a member function of the same class. The pointer needs to be passed to a function as a void (*)(). Example:

//CallFunc takes a void (*)() argument           
class testClass {        
public:   
    void aFunc2;   
    void aFunc1;  
}  
void testClass:aFunc2(){  
    callFunc(this.*aFunc1); // How should this be done?  
}  
void testClass:aFunc1(){  
    int someVariable = 1;  
}

I'm trying to do this in GCC 4.0.1. Also, the member function being called can't be static because it references non-static variables in the class that it is part of. (In case you are wondering, the specific instance in which I need this is where I need to be able to pass a member function of a class to the GLUT function glutDisplayFunc() )

I read this article once and found it very interesting:

http://www.codeproject.com/KB/cpp/FastDelegate.aspx

Also, for a FAQ about pointer to member functions, read this:

http://www.parashift.com/c++-faq-lite/pointers-to-members.html

To take pointer to member function you need following syntax:

callFunc(&testClass::aFunc1); 

But note, that to invoke member function you need have class instance. So callFunc needs 2 parameters (I'm using template but you can change it to testClass):

template <class T> 
void callFunc(T*inst, void (T::*member)())
{
    (inst->*member)();
}

So correct call of callFunc looks like:

void testClass::aFunc2()
{
    callFunc(this, &testClass::aFunc1); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM