我想了解事件处理/回调中的C++ 0x std :: bind和std :: function用法。所以我正在检查一些代码片段,并遇到了一些我不能完全理解的有趣的地方。std ::绑定和std ::函数在回调中的用法
比方说,我们有:
class EventHandler
{
public:
template<typename Event, typename Listener>
bool bindEvent (const Listener& function)
{
if (std::is_array<Event>::value)
{
std::cout << "You cannot register an array as an event type" << std::endl;
return false;
}
if (std::is_convertible<Listener, std::function<void (Event&)>>::value)
{
std::cout << "Invalid callback for this event type" << std::endl;
return false;
}
listeners.insert(std::make_pair(&typeid(typename std::decay<Event>::type),
[=](void* ev) { function(*static_cast<Event*>(ev)); }));
}
private:
// for each event type, we have a list of callbacks
// these callbacks are of the form std::function<void (void*)>
// because we will convert between the &event and void*
typedef std::function <void (void*)> fun;
std::unordered_multimap <const std::type_info*, fun> listeners;
};
// example of an event type
struct KeyboardEvent
{
int keyCode;
};
// example of an event callback
void do_key (const KeyboardEvent &event)
{
std::cout << "I am working" << std::endl;
}
int main (int argc, char** argv)
{
EventHandler handler;
handler.bindEvent<KeyboardEvent> (&do_key); // fixed typo
return 0;
}
问题:不监听在这部分持有什么类型的?
template<typename Event, typename Listener>
bool bindEvent(const Listener& function)
由于主要方法,我们调用这个函数只。
PS:另外,这段代码在std :: is_convertible部分失败。 (据我所知,因为不匹配的类型,从habindEvent<KeyboardEvent> (&do_key);
的确很不错。之前从未想过这件事。 – legion
或者你可以使用static_assert来代替,并且在编译时优雅地失败并且不那么神秘的消息 – David