如果我有这些声明和定义:
enum Events
{
INIT,
RENDER
};
struct EventBase
{
typedef void (EventBase::*event_callback_type)();
~EventBase() {}
virtual void init() { assert(0); }
virtual void render() { assert(0); }
};
template <enum Events>
struct EventTraits
{
static EventBase::event_callback_type const event_callback;
};
// in a .cpp file
template <>
EventBase::event_callback_type const
EventTraits<INIT>::event_callback(
&EventBase::init);
template <>
EventBase::event_callback_type const
EventTraits<RENDER>::event_callback(
&EventBase::render);
// in another class *i are pointers to objects that inherit EventBase
template <enum Events event>
inline void EventNotifier::notify()
{
for (events_type::const_iterator i(event_handlers[event].begin());
i != event_handlers[event].begin() + num_event_handlers[event];
++i)
{
((*i)->*EventTraits<event>::event_callback)();
if ((*i)->num_event_handlers[event])
{
(*i)->notify<event>();
}
// else do nothing
}
}
说,事件 RENDER 需要尽可能快的处理,你认为是否值得做一个成员模板专业化:
template <>
inline void EventNotifier::notify<RENDER>()
{
for (events_type::const_iterator i(event_handlers[RENDER].begin());
i != event_handlers[RENDER].begin() + num_event_handlers[RENDER];
++i)
{
(*i)->render();
if ((*i)->num_event_handlers[RENDER])
{
(*i)->notify<RENDER>();
}
// else do nothing
}
}
这不需要获取指向成员函数的静态指针。或者我应该这样做:
template <enum Events>
struct EventTraits
{
static EventBase::event_callback_type event_callback();
};
并专门化结构模板?