Since the c++0x supports the Variadic function, it's the very time to improve original C + + Event system.
The thought is as same as [2.0].
This is the code list.
The root Object:
Class TObject
{public
:
tobject ()
{
//Dummy
}
Virtual ~tobject ()
{
}
};
And then Event declaration:
#include "Object.h" #include <memory> namespace Igame {template<typename T_ret, TypeName ...
params> struct Teventhandler {typedef t_ret Type;
typedef t_ret (TObject::* Function) (PARAMS ...);
Std::shared_ptr<object> _target;
Function _function; __inline__ T_ret operator () (PARAMS ... PARAMS) {if (_target!= nullptr && _function!=) Return (_
Target.get ()->*_function) (params ...);
}
}; Template<typename T_ret, TypeName ...
params> struct Event {typedef teventhandler<t_ret, params...> Handler;
typedef typename Handler::function Function;
Handler _handler;
Template <typename T_f = Function, typename t_arg> __inline__ t_f castfunction (T_arg Arg) {return (t_f) arg; } template<typename t_func> __inline__ void bind (std::shared_ptr<tobject> tag, T_func FUNC) {_han
Dler = {tag, castfunction (func)}; } __inline__ T_ret operator () (params...params) {return _haNdler (params ...);
}
}; }//NS Igame
Compared with 2.0, it's more elegant, more lightweight.
Note:under g++, the inline qualifier may not work as your wish.
Now, let's rock:
Class A:public TObject
{public
:
void foo (int x)
{
//cout << "foo:" << x << Endl;
}
void Foo2 (std::function<void (int) > Func)
{
func ();
}
;
Class B:public TObject
{public
:
using MyEvent = event<void, int>;
Using Myfuncevent = event<void, std::function<void (int) >>;
MyEvent event;
Myfuncevent funcevent;
void testevent (int x)
{
cout << "FXX:" << x << Endl;
event (x);
}
void Testfuncevent (std::function<void (int) > Func)
{
funcevent ([This, func] (int x) {
cout< <this->message<<endl;
Func (x);
});
}
;
The following code shows how to use the Event system:
Std::shared_ptr<a> A (new A ());
Std::shared_ptr<b> B (new B ());
B->event.bind (A, &a::foo);
B->funcevent.bind (A, &a::foo2);
B->testevent (m);
int x =;
B->testfuncevent ([;] (int val) {
val = x;
});
Actually, this implementation of the Event are more like the std::function<> but a little improvement of performance:230 93MS V.s 29146.2ms for calling of 0xEFFFFFFF times in my ASUS q200e laptop. On the other words, 5.73521ns v.s 7.23853ns for/per calling.
And more straightly than Std::function<> After all, the virtual function calling consumes 4.29958ns to per calling. As a syntactic sugar, my event model works pretty.