c++ - Cannot call a member function pointer on a object typecasted as void * -


so reason want use member function pointer invoke function place type of object not known , objects treated void * objects. unable though rationally seems function pointers point address of subroutine , hence type of object should immaterial. assumption system has set "this" pointer object on member function pointer called. below code. how can achieve want

class c2 {     public:        int y;        void setvalue(int); };  void c2::setvalue(int k) {     cout<<"setting value inside c2"<<endl;     y=k; }  int main() {     void (c2::*f)(int);     c2 *ob=new c2();     void *ob2=(void *)ob;     f = &c2::setvalue;     ((ob2)->*f)(10); } 

this code not compiling vc++ compiler error

error c2296: '->*' : illegal, left operand has type 'void *'

well simple fix problem static_cast ob2 right type, since need know class function belongs anyway:

(static_cast<c2*>(ob2)->*f)(10); 

you automate templates:

template <typename ret, class c, typename... params, typename... args> ret callmemptr (ret (c::*fun) (params...), void* obj, args&&... args) {     return (static_cast<c*>(obj)->*fun)(std::forward<args>(args)...);    }  //usage callmemptr(f,ob2,10); 

however, seems odd approach take. might better off using inheritance or form of type erasure.


Comments