Is it possible to use a function pointer to point at a non-static member function? I would like to point at a member function that uses non-static objects and variables from the class...static member functions cannot do this...
I have a member function that points at one of four static member functions. The problem is that the data to be used by each of the four member functions is non-static so the static member functions will not access them...
Can I point at non-static member functions?
Also, the class instance is a pointer...here is my code:
class CRoutine{
int m_index;
...
BOOL (*CallRoutine(char opcode))(DWORD, float, float, float);
static BOOL Update(DWORD, float, float, float);
static BOOL Transition(DWORD, float, float, float);
static BOOL Revert(DWORD, float, float, float);
static BOOL Sequence(DWORD, float, float, float);
...
};
BOOL (*CRoutine::CallRoutine(char opcode))(DWORD, float, float, float)
{
switch ( opcode )
{
case 0:
return &CRoutine::Update;
case 1:
return &CRoutine::Transition;
case 2:
return &CRoutine::Revert;
case 3:
return &CRoutine::Sequence;
default:
return &CRoutine::Update;
}
}
BOOL CRoutine::Update(DWORD AnimSetIndex, float time, float tTime, float shift)
{
MessageBox(NULL, L"Updating", L"Routine #1", MB_OK);
CRoutine::m_index++; // Error thrown here...
return true;
}
BOOL CRoutine::Transition(DWORD AnimSetIndex, float time, float tTime, float shift)
{
MessageBox(NULL, L"Transitioning", L"Routine #2", MB_OK);
return true;
}
BOOL CRoutine::Revert(DWORD AnimSetIndex, float time, float tTime, float shift)
{
MessageBox(NULL, L"Reverting", L"Routine #3", MB_OK);
return true;
}
BOOL CRoutine::Sequence(DWORD AnimSetIndex, float time, float tTime, float shift)
{
MessageBox(NULL, L"Sequencing", L"Routine #4", MB_OK);
return true;
}
The error thrown above is: error C2597: illegal reference to non-static member 'CRoutine::m_index'
Yes as long as you can modify the type in which it is stored.
Using the std::function abstract you can bind to anything that meets a certain signature (ie take x return y). be it functor, lambda, bound member function or free function.
struct bar{
void foo(){
std::cout << "HI" << std::endl;
}
};
int main(){
bar b;
//using std::function instead of a func*
std::function<void()> func(
std::bind(&bar::foo, &b));
func();
}
Note the use of std::function require C++11, boost has a very similar version too that can be used with C++98
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.