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語(yǔ)言修煉之路數(shù)據(jù)類(lèi)型悟正法 解析存儲(chǔ)定風(fēng)魔下篇
使用編程語(yǔ)言進(jìn)行編程時(shí),需要用到各種變量來(lái)存儲(chǔ)各種信息。變量保留的是它所存儲(chǔ)的值的內(nèi)存位置。這意味著,當(dāng)您創(chuàng)建一個(gè)變量時(shí),就會(huì)在內(nèi)存中保留一些空間。您可能需要存儲(chǔ)各種數(shù)據(jù)類(lèi)型的信息,操作系統(tǒng)會(huì)根據(jù)變量的數(shù)據(jù)類(lèi)型,來(lái)分配內(nèi)存和決定在保留內(nèi)存中存儲(chǔ)什么2022-02-02基于c++ ege圖形庫(kù)實(shí)現(xiàn)五子棋游戲
這篇文章主要為大家詳細(xì)介紹了基于c++ ege圖形庫(kù)實(shí)現(xiàn)五子棋游戲,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-12-12c語(yǔ)言在控制臺(tái)判定鼠標(biāo)左鍵的小例子
c語(yǔ)言在控制臺(tái)判定鼠標(biāo)左鍵的小例子,需要的朋友可以參考一下2013-06-06C++11?condition_variable條件變量的用法說(shuō)明
這篇文章主要介紹了C++11?condition_variable條件變量的用法說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07VC中實(shí)現(xiàn)GB2312、BIG5、Unicode編碼轉(zhuǎn)換的方法
這篇文章主要介紹了VC中實(shí)現(xiàn)GB2312、BIG5、Unicode編碼轉(zhuǎn)換的方法,該功能非常實(shí)用,需要的朋友可以參考下2014-07-07C/C++程序開(kāi)發(fā)中實(shí)現(xiàn)信息隱藏的三種類(lèi)型
這篇文章主要介紹了C/C++程序開(kāi)發(fā)中實(shí)現(xiàn)信息隱藏的三種類(lèi)型的相關(guān)資料,需要的朋友可以參考下2016-02-02C++中strlen函數(shù)的三種實(shí)現(xiàn)方法
在C語(yǔ)言中我們要獲取字符串的長(zhǎng)度,可以使用strlen?函數(shù),strlen?函數(shù)計(jì)算字符串的長(zhǎng)度時(shí),直到空結(jié)束字符,但不包括空結(jié)束字符,因?yàn)閟trlen函數(shù)時(shí)不包含最后的結(jié)束字符的,因此一般使用strlen函數(shù)計(jì)算的字符串的長(zhǎng)度會(huì)比使用sizeof計(jì)算的字符串的字節(jié)數(shù)要小2022-05-05