Game Development Reference
In-Depth Information
The point of using this friend function is to reduce the amount of code we must write each time we
would like to send an Event . If we did not have this friend function, we would need to write the six
lines it contains each time. Instead of this we can simply write
SendEvent(someEvent);
The friend function also safely checks that the Singleton EventManager class has been
created. This is useful, as there might be situations in which you might like to test without the
EventManager . The SendEvent function itself is relatively simple and calls the SendEvent private
member on the EventManager class. This is a benefit of the friend function: It can access
the private members and methods of any class it is a friend of. Using this technique you can
ensure that only the public friend functions can be used to interact with the EventManager .
Listing 21-15 shows the RegisterEvent function, which is equally straightforward.
Listing 21-15. The RegisterEvent Function
inline bool RegisterEvent(EventID eventId)
{
bool added = false;
EventManager* pEventManager = EventManager::GetSingletonPtr();
assert(pEventManager);
if (pEventManager)
{
added = pEventManager->RegisterEvent(eventId);
}
return added;
}
The other three functions interact with the EventManager in a similar way; however, they do have a
significant difference. They contain a little template metaprogramming. Listing 21-16 shows all three
remaining functions.
Listing 21-16. The SendEventToHandler , AttachEvent , and DetachEvent friend Functions
template <typename T>
inline void SendEventToHandler(EventID eventId, T* eventHandler)
{
static_assert(std::is_base_of<EventHandler, T>::value,
"Class provided is not derived from EventHandler");
EventManager* pEventManager = EventManager::GetSingletonPtr();
assert(pEventManager);
if (pEventManager)
{
pEventManager->SendEventToHandler(
eventId, *static_cast<EventHandler*>(eventHandler));
}
}
 
Search WWH ::




Custom Search