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

时间:2021-05-20

复制代码 代码如下:
#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);
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章