C++保存成员函数指针
成员函数指针保存:
char mf_addr_[16];
void (DestT::*memfun)(int);
memcpy(&mf_addr_,&memfun,sizeof(memfun));
DEMO:
class Signal1{
public:
template <class DestT>
void connect(DestT* dest,void (DestT::*memfun)(int)){
inst_ = (void*)dest;
assert(sizeof(memfun)<=sizeof(mf_addr_));
memcpy(&mf_addr_,&memfun,sizeof(memfun));
call_fun_ = &call_mf<DestT>;
}
void emit(int arg) const{
call_fun_(inst_,mf_addr_,arg);
}
private:
void *inst_;
char mf_addr_[16];
void (*call_fun_)(void *,const char* ,int);
template <class DestT> static void call_mf(void *inst,const char* memfun,int arg){
void (DestT::*mf)(int);
memcpy(&mf,memfun,sizeof(mf));
((static_cast<DestT*>(inst))->*mf)(arg);
}
};
class Sender{
public:
Signal1 s_;
void doSignal(int i){
s_.emit(i);
}
};
class Receiver{
public:
void onSignal(int i){
cout<<"signal with "<<i<<endl;
}
};
int main(int argc,char* argv[]){
Sender sender;
Receiver receiver;
sender.s_.connect(&receiver, &Receiver::onSignal);
sender.doSignal(5);
return 0;
}