不关是c.还是c++那么在内存中,数据和程序代码是分开的,代码段和数据段是分开存储的,你声明一个类,他的大小只是数据段数据的大小.既然是这样,那么问题就可以解决了.
代码如下
class EventArgs
{
public:
EventArgs(void) : handled(false) {}
virtual ~EventArgs(void) {}
bool handled;
};
class SlotFunctorBase
{
public:
virtual ~SlotFunctorBase() {};
virtual bool operator()(const EventArgs& args) = 0;
};
template<typename T>
class FunctorPointerSlot : public SlotFunctorBase
{
public:
FunctorPointerSlot(T* functor) :
d_functor(functor)
{}
virtual bool operator()(const EventArgs& args)
{
return (*d_functor)(args);
}
private:
T* d_functor;
};
template<typename T>
class MemberFunctionSlot : public SlotFunctorBase
{
public:
//! Member function slot type.
typedef bool(T::*MemberFunctionType)(const EventArgs&);
MemberFunctionSlot(MemberFunctionType func, T* obj) :
m_lpFunction(func),
d_object(obj)
{}
virtual bool operator()(const EventArgs& args)
{
return (d_object->*m_lpFunction)(args);
}
private:
MemberFunctionType m_lpFunction;
T* d_object;
};
class SubscriberSlot
{
public:
SubscriberSlot(){}
~SubscriberSlot(){
delete d_functor_impl;
};
bool operator()(const EventArgs& args) const
{
return (*d_functor_impl)(args);
}
bool connected() const
{
return d_functor_impl != 0;
}
template<class T>
SubscriberSlot(bool (T::*function)(const EventArgs&), T* obj) :
d_functor_impl(new MemberFunctionSlot<T>(function, obj))
{}
template<class T>
SubscriberSlot(T* functor) :
d_functor_impl(new FunctorPointerSlot<T>(functor))
{}
private:
//! Points to the internal functor object to which we are bound
SlotFunctorBase* d_functor_impl;
};
bool testI(const EventArgs& _art)
{
return true;
}
class CTest
{
public:
static bool Arg(const EventArgs& ev)
{
return true;
}
void Test()
{
SubscriberSlot fun(testI);
EventArgs test;
fun(test);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
CTest test;
test.Test();
return 0;
}