| template <typename MF_T, typename ARG1 = VoidType, typename ARG2 = VoidType> class MulticastDelegateT : public DelegateT_<MF_T> { typedef DelegateT_<MF_T> Delegate; typedef std::list<Delegate> Delegates_t; protected: MulticastDelegateT() {} public: MulticastDelegateT(Object& o, const MF_T& mf) : Delegate(o, mf) {} MulticastDelegateT& operator+=(const Delegate& d) { m_delegates.push_back(d); return *this; } private: Delegates_t m_delegates; }; |
| void operator()(ARG1 v1 = VoidType(), ARG2 v2 = VoidType()) const { for (Delegates_t::const_iterator it = m_delegates.begin(); it != m_delegates.end(); ++it) (it->Target()).Invoke(it->Method(), v1, v2); } |
| const Delegate& d = *it; d.Invoke(d.Method(), v1, v2); |
| for (int i=0; i<m_delegates.size(); i++) Delegate d = m_delegates[i]; |
| template <typename ARG1, typename ARG2> void Invoke_(ARG1 v1 = ARG1(), ARG2 v2 = ARG2()) const { this->Invoke(m_method, v1, v2); } |
| template <typename MF_T, typename ARG1 = VoidType, typename ARG2 = VoidType> struct DelegateT : public MulticastDelegateT<MF_T, ARG1, ARG2> { DelegateT(Object& o, const MF_T& mf) : MulticastDelegateT<MF_T, ARG1, ARG2>(o, mf) {} DelegateT() {} typedef DelegateT<MF_T, ARG1, ARG2> Event; }; |
| class DelegatesAndEvents { // C#: public delegate void PrintString(string s); typedef DelegateT<Object::void1_T<std::string>::mf_t, std::string> PrintString_; public: template <typename OBJECT> static PrintString_ PrintString(OBJECT& o, void (OBJECT::*mf)(std::string)) { return PrintString_(o, static_cast<Object::void1_T<std::string>::mf_t>(mf)); } // C#: public event PrintString MyPrintString; PrintString_::Event MyPrintString; void FirePrintString(std::string s) { MyPrintString(s); } }; |
| struct MyDelegates : public ObjectT<MyDelegates> { // ... Name omitted... void SimpleDelegateFunction(std::string s) { printf("SimpleDelegateFunction called from %s, string=%s\n", m_name.c_str(), s.c_str()); } // ... more methods ... }; void CppStyle() { DelegatesAndEvents dae; MyDelegates d; d.Name() = "Obj1"; dae.MyPrintString += DelegatesAndEvents::PrintString (d, &MyDelegates::SimpleDelegateFunction); // ... more code similar to the above few lines ... dae.FirePrintString("Event fired!"); } |