Cannot call pointer to member function from static method

It is difficult for me to call a pointer to a member function for an object that was different from void* . Example below:

 class Test { public: Test(int pointTo) { if (pointTo == 1) function = &Test::Function1; else function = &Test::Function2; } static void CallIt(void* cStyle) { Test* t(static_cast<Test*>(cStyle)); (t->*function)();// error C2568: '->*': unable to resolve function overload } void CallIt() { (this->*function)();// Works just fine } private: typedef void (Test::*ptrToMemberFunc)(); ptrToMemberFunc function; void Function1() { std::cout << "Function 1" << std::endl; } void Function2() { std::cout << "Function 2" << std::endl; } }; int main() { Test t1(1); Test t2(2); Test::CallIt(static_cast<void*>(&t1)); Test::CallIt(static_cast<void*>(&t2)); t1.CallIt(); t2.CallIt(); return 0; } 

What happens when an object is moved to void* and vice versa? Why can I no longer call a pointer to a member function?

EDIT:

Changing CallIt() as follows allows the program to compile, but I'm still wondering why the original did not work.

 static void CallIt(void* cStyle) { Test* t(static_cast<Test*>(cStyle)); Test::ptrToMemberFunc pf(t->function); (t->*pf)(); } 
+8
c ++ pointer-to-member
source share
1 answer
 main.cpp:17:14: error: invalid use of member 'function' in static member function (t->*function)();// error C2568: '->*': unable to resolve function overload ^~~~~~~~ 

function is a non-static data element, so you cannot access it from a static function.

If you want to access the t function , you can do it like this:

  (t->*(t->function))(); 
+10
source share

All Articles