亲宝软件园·资讯

展开

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

人气:0
想了解c++传递函数指针和bind的示例的相关内容吗,在本文为您仔细讲解c++传递函数指针的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:函数指针,下面大家一起来学习吧。

复制代码 代码如下:

#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);
}

加载全部内容

相关教程
猜你喜欢
用户评论