c++傳遞函數指針和bind的示例。本站提示廣大學習愛好者:(c++傳遞函數指針和bind的示例)文章只能為提供參考,不一定能成為您想要的結果。以下是c++傳遞函數指針和bind的示例正文
#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);
}