学习duilib之前 ,先看了下 大部分的控件消息 的转发,看到了这样的代码:
CSliderUI* pSilder = static_cast<CSliderUI*>(m_pm.FindControl(_T("alpha_controlor")));
if( pSilder ) pSilder->OnNotify += MakeDelegate(this, &CFrameWindowWnd::OnAlphaChanged);
首先找到 你操作的控件(FindControl) 后,后边MakeDelegate 添加了代理函数,操作滚动条时,就会处发 自己实现的OnAlphaChanged函数,今天看了其中的实现,发现不错,因为像c#那样的语言都有委托的实现,c++中没有,于是就借鉴duilib的实现,分析其中的代码自己简单实现了c++的委托,原理 其实就像c++中的函数回调封装,利用函数对象与函数重载,部分代码:
class DUILIB_API CEventSource
{
typedef bool (*FnType)(void*);
public:
~CEventSource();
operator bool();
void operator+= (const CDelegateBase& d); // add const for gcc
void operator+= (FnType pFn);
void operator-= (const CDelegateBase& d);
void operator-= (FnType pFn);
bool operator() (void* param);
protected:
CDuiPtrArray m_aDelegates;
};
实现 operator+= ,operator-= ,operator() 将自己的函数添加到 代理中,下面放上自己的简单实现:
#include "stdafx.h"
#include <functional>
#include <vector>
#include <memory>
#include <algorithm>
using namespace std;
typedef std::function<bool(void*)> FUNC;
class CDelegate;
typedef std::shared_ptr<CDelegate> cdptr;
class CDelegate
{
public:
CDelegate( FUNC pFn)
{
m_pFn = pFn;
}
CDelegate(const CDelegate& rhs)
{
m_pFn = rhs.m_pFn;
}
virtual ~CDelegate(){}
bool operator() (void* param)
{
m_pFn(param);
return true;
}
private:
FUNC m_pFn;
};
cdptr MakeDelegate( FUNC pFn)
{
return make_shared<CDelegate>(pFn);
}
class CEventSource
{
public:
~CEventSource()
{
m_aDelegates.clear();
}
void operator+= (cdptr cdb)
{
auto rtn = std::find_if(m_aDelegates.begin(), m_aDelegates.end(), [&](cdptr cd) {
if (cd == cdb) { return true; }
});
if (rtn != m_aDelegates.end())
{
return;
}
m_aDelegates.push_back(cdb);
}
void operator-= (cdptr cbd)
{
auto rtn = std::find_if(m_aDelegates.begin(), m_aDelegates.end(), [&](cdptr cd) {
if (cd == cbd) {
return true;
}
});
m_aDelegates.erase(rtn);
}
bool operator() (void* param)
{
for (int i = 0; i < m_aDelegates.size(); i++) {
cdptr pObject = m_aDelegates[i];
if (&pObject && !(pObject->operator())(param)) return false;
}
return true;
}
protected:
vector<cdptr> m_aDelegates;
};
class TestObj
{
public:
bool testprint(void* param)
{
int* a = static_cast<int*>(param);
printf("a= %d\n",*a);
return true;
}
void pubTest()
{
m_es += MakeDelegate(std::bind(&TestObj::testprint,this,std::placeholders::_1));
m_es -= MakeDelegate(std::bind(&TestObj::testprint, this, std::placeholders::_1));
}
CEventSource m_es;
};
int main()
{
TestObj to;
to.pubTest();
int abc = 2;
to.m_es(&abc);
getchar();
return 0;
}
采用 c++11 的 std::function,c++11确实 让代码好写,并易于理解~