我想了解事件處理/回調中的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