Game Development Reference
In-Depth Information
The Event Listener Delegates
Events and event data need to go somewhere, and they always go to event listener
delegate functions. A delegate function is basically a function pointer that can be cou-
pled with an object pointer and used as a callback. They are used quite extensively in
C# and other .NET applications. C++ can do C-style function pointers as well as C++
functor objects, but it tends to fall apart when you try to encapsulate pointers to
member functions. The problem is that the C++ compiler needs to know the type
of the function pointer, which defeats our purposes. What we really want is a C#-
style delegate where we can define a function signature and not care where the func-
tion comes from, as long as it conforms to our signature. C++ can ' t do this without a
lot of template magic.
Fortunately, someone has already solved this problem for us! Don Clugston wrote a
great article on The Code Project about fast C++ delegates and was kind enough to
publish the code for public use. It has no license whatsoever, so you can use it in
commercial applications. The article itself is fantastic and worth a read, although I
warn you that it covers some pretty advanced C++ stuff. It
'
s not for the feint of
heart:
http://www.codeproject.com/KB/cpp/FastDelegate.aspx
All event
listener delegate functions must conform to the following function
prototype:
typedef shared_ptr<IEventData> IEventDataPtr; // smart ptr to IEventData
void Delegate(IEventDataPtr pEventData);
The name of the function doesn
t matter, nor does the name of the parameter or
even what class it comes from. It could be a virtual function, a static function, a
global function, or just a regular member function. That
'
s the beauty of the fast dele-
gate library! To declare this function signature as a delegate, we typedef it like so:
'
typedef fastdelegate::FastDelegate1<IEventDataPtr> EventListenerDelegate;
Everything in the fast delegate library is under the fastdelegate namespace. The
FastDelegate1 template is the help class used to bind the runtime object (if it
exists) with the appropriate function pointer. The
you see there is because there
is one parameter. If there were two parameters, you would use FastDelegate2 , and
so on. This is required mostly for compiler compatibility. The template parameter is
the parameter type you want to pass into the function. There is an optional addi-
tional parameter for the return value, which we
1
re not using here. EventListener-
Delegate is now a typedef of the delegate type.
'
 
 
Search WWH ::




Custom Search