C++实现的委托机制(2)(二)

2014-11-24 12:43:47 · 作者: · 浏览: 1
delete (*iter);
(*iter) = 0;
}
}
}
CMultiDelegate2 & operator+=(IDelegate* _delegate)
{
for (ListDelegateIterator iter=mListDelegates.begin(); iter!=mListDelegates.end(); ++iter)
{
if ((*iter) && (*iter)->compare(_delegate))
{
delete _delegate;
return *this;
//MYGUI_ASSERT(false, "dublicate delegate");
}
}
mListDelegates.push_back(_delegate);
return *this;
}
CMultiDelegate2 & operator-=(IDelegate* _delegate)
{
for (ListDelegateIterator iter=mListDelegates.begin(); iter!=mListDelegates.end(); ++iter)
{
if ((*iter) && (*iter)->compare(_delegate))
{
if ((*iter) != _delegate) delete (*iter);
(*iter) = 0;
break;
}
}
delete _delegate;
return *this;
}
void operator()( TP1 p1, TP2 p2 )
{
ListDelegateIterator iter = mListDelegates.begin();
while (iter != mListDelegates.end())
{
if (0 == (*iter))
{
iter = mListDelegates.erase(iter);
}
else
{
(*iter)->invoke( p1, p2 );
++iter;
}
}
}
private:
CMultiDelegate2 (const CMultiDelegate2 & _event);
CMultiDelegate2 & operator=(const CMultiDelegate2 & _event);
private:
ListDelegate mListDelegates;
};
template
class IDelegate2
{
public:
virtual ~IDelegate2() { }
virtual bool isType( const std::type_info& _type) = 0;
virtual void invoke( TP1 p1, TP2 p2 ) = 0;
virtual bool compare( IDelegate2 *_delegate) const = 0;
};
template
class CStaticDelegate2 : public IDelegate2
{
public:
typedef void (*Func)( TP1 p1, TP2 p2 );
CStaticDelegate2 (Func _func) : mFunc(_func) { }
virtual bool isType( const std::type_info& _type) { return typeid( CStaticDelegate2 ) == _type; }
virtual void invoke( TP1 p1, TP2 p2 )
{
mFunc( p1, p2 );
}
virtual bool compare( IDelegate2 *_delegate) const
{
if (0 == _delegate || !_delegate->isType(typeid(CStaticDelegate2 )) ) return false;
CStaticDelegate2 * cast = static_cast *>(_delegate);
return cast->mFunc == mFunc;
}
virtual bool compare(IDelegateUnlink * _unlink) const { return false; }
private:
Func mFunc;
};
template
class CMethodDelegate2 : public IDelegate2
{
public:
typedef void (T::*Method)( TP1 p1, TP2 p2 );
CMethodDelegate2(T * _object, Method _method) : mObject(_object), mMethod(_method) { }
virtual bool isType( const std::type_info& _type) { return typeid( CMethodDelegate2 ) == _type; }
virtual void invoke( TP1 p1, TP2 p2 )
{
(mObject->*mMethod)( p1, p2 );
}
virtual bool compare( IDelegate2 * _delegate) const
{
if (0 == _delegate || !_delegate->isType(typeid(CMethodDelegate2 )) ) return false;
CMethodDelegate2 * cast = static_cast< CMethodDelegate2 * >(_delegate);
return cast->mObject == mObject && cast->mMethod == mMethod;
}
private:
T * mObject;
Method mMethod;
};
template
inline delegates::IDelegate2 * newDelegate( void (*_func)( TP1 p1, TP2 p2 ) )
{
return new delegates::CStaticDelegate2 (_func);
}
template
inline delegates: