C++类hook功能(本质是回调)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010164190/article/details/88354809
#include <iostream>
#include <vector>
#include <map>
using namespace std;
class StructA{
public:
  int i;
  StructA(int i){
    this->i = i;
    cout<< "StructA(int), line = "<< __LINE__<< endl;
  };
  ~StructA(){ cout <<"~StructA "<< endl;};
  void process__nop(){ cout << __FUNCTION__ <<"() is Called Success!" <<  endl;}
  void process__hook(){ cout << __FUNCTION__ <<"() is Called Success!" <<  endl;}
  void process(){(this->*mHook)();}
  void set_nop(){mHook = &StructA::process__nop;}
  void set_hook(){mHook = &StructA::process__hook;   }
  //using定义类型别名,和typedef作用一样。
  using process_hook_t = void(StructA::*)();
  process_hook_t mHook;
};

int main(){
  map<int, shared_ptr<StructA>> mStrA;
  mStrA.insert(pair<int, shared_ptr<StructA>>(0,make_shared<StructA>(180)));
  for(auto &mA : mStrA)
    cout <<"index = " << mA.first << " i = " << mA.second->i << endl;
  //访问时注意下标mStrA[i].
  mStrA[0]->set_nop();
  mStrA[0]->process();
  
  //hook
  mStrA[0]->set_hook();
  mStrA[0]->process();  
  return 0;
}

猜你喜欢

转载自blog.csdn.net/u010164190/article/details/88354809