c++傳遞函數(shù)指針和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);
}
相關(guān)文章
C語言修煉之路數(shù)據(jù)類型悟正法 解析存儲定風(fēng)魔下篇
使用編程語言進(jìn)行編程時,需要用到各種變量來存儲各種信息。變量保留的是它所存儲的值的內(nèi)存位置。這意味著,當(dāng)您創(chuàng)建一個變量時,就會在內(nèi)存中保留一些空間。您可能需要存儲各種數(shù)據(jù)類型的信息,操作系統(tǒng)會根據(jù)變量的數(shù)據(jù)類型,來分配內(nèi)存和決定在保留內(nèi)存中存儲什么2022-02-02C++11?condition_variable條件變量的用法說明
這篇文章主要介紹了C++11?condition_variable條件變量的用法說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07VC中實現(xiàn)GB2312、BIG5、Unicode編碼轉(zhuǎn)換的方法
這篇文章主要介紹了VC中實現(xiàn)GB2312、BIG5、Unicode編碼轉(zhuǎn)換的方法,該功能非常實用,需要的朋友可以參考下2014-07-07C/C++程序開發(fā)中實現(xiàn)信息隱藏的三種類型
這篇文章主要介紹了C/C++程序開發(fā)中實現(xiàn)信息隱藏的三種類型的相關(guān)資料,需要的朋友可以參考下2016-02-02C++中strlen函數(shù)的三種實現(xiàn)方法
在C語言中我們要獲取字符串的長度,可以使用strlen?函數(shù),strlen?函數(shù)計算字符串的長度時,直到空結(jié)束字符,但不包括空結(jié)束字符,因為strlen函數(shù)時不包含最后的結(jié)束字符的,因此一般使用strlen函數(shù)計算的字符串的長度會比使用sizeof計算的字符串的字節(jié)數(shù)要小2022-05-05