Game Development Reference
In-Depth Information
template <typename T>
inline void AttachEvent(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->AttachEvent(eventId, *static_cast<EventHandler*>(eventHandler));
}
}
template <typename T>
inline void DetachEvent(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->DetachEvent(eventId, *static_cast<EventHandler*>(eventHandler));
}
}
The important line in these three methods is the static_assert and the code it contains:
static_assert(std::is_base_of<EventHandler, T>::value, "Class provided is not derived from EventHandler");
The is_base_of keyword is actually a C++11 built-in template metaprogram. It is used to
determine at compile time if a type is derived from another. In our case we supply a type to the
templates using the typename T syntax as usual and then we pass this type T into the second
parameter of is_base_of . The template compiler will calculate if the EventHandler class is a parent
of the supplied class and set the value variable to be either true or false . Using this template
metaprogram ensures that we can never attach or detach objects that are not derived from
EventHandler by combining it with static_assert , which will throw an error when we are building
our game.
The EventManager class is complete, but before you can use it I'm going to show you how you can
write your own template metaprogram to calculate unique event IDs.
 
Search WWH ::




Custom Search