雷火电竞-中国电竞赛事及体育赛事平台

歡迎來(lái)到入門(mén)教程網(wǎng)!

C語(yǔ)言

當(dāng)前位置:主頁(yè) > 軟件編程 > C語(yǔ)言 >

c++傳遞函數(shù)指針和bind的示例

來(lái)源:本站原創(chuàng)|時(shí)間:2020-01-10|欄目:C語(yǔ)言|點(diǎn)擊:

復(fù)制代碼 代碼如下:

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

上一篇:c++實(shí)現(xiàn)逐行讀取配置文件寫(xiě)入內(nèi)存的示例

欄    目:C語(yǔ)言

下一篇:使用UART與PC通信實(shí)現(xiàn)msp430g2553單片機(jī)超聲波測(cè)距示例

本文標(biāo)題:c++傳遞函數(shù)指針和bind的示例

本文地址:http://www.jygsgssxh.com/a1/Cyuyan/3656.html

網(wǎng)頁(yè)制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語(yǔ)言數(shù)據(jù)庫(kù)服務(wù)器

如果侵犯了您的權(quán)利,請(qǐng)與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有