c++传递函数指针和bind的示例

时间:2022-01-31 09:05:28

复制代码 代码如下:


#include <algorithm>
class TestClass
{
public:
 int Sub(int x, int y) {
  return y - x;
 }
 void InitAndTest() {
  PrintWithClassMemberFunction(&TestClass::Sub);
  PrintWithClassPointer(this);
 }

 

 // call: PrintWithClassMemberFunction(&TestClass::Sub);
 void PrintWithClassMemberFunction(int (TestClass::*f)(int, int)) {
  // add 'this' pointer
  auto rel = (this->*f)(12, 13);
  AtlTrace("[%d]\n", rel);

  // bind with member function pointer into map
  auto funBind = std::bind(f, this, std::placeholders::_1, std::placeholders::_2);
  m_mapFun["PrintWithClassMemberFunction"] = funBind;
 }

 void PrintWithClassPointer(TestClass *pointInstance) {
  auto rel = pointInstance->Sub(20, 30);
  AtlTrace("[%d]\n", rel);

  auto funBind = std::bind(&TestClass::Sub, pointInstance, std::placeholders::_1, std::placeholders::_2);
  m_mapFun["PrintWithClassPointer"] = funBind;
 }

 void CallBindFun(int a, int b) {
  std::for_each(
   m_mapFun.begin(), m_mapFun.end(), [&a, &b](decltype(*m_mapFun.begin()) it) {
    AtlTrace("[%s] %d\n", it.first.c_str(), it.second(a, b));
  });
 }

 std::map<std::string, std::function<int (int, int)>> m_mapFun;
};


int _tmain(int argc, _TCHAR* argv[])
{
 TestClass tc;
 tc.InitAndTest();
 tc.CallBindFun(64, 128);
}