原生C++ 11事件 - 事件没事势必会引发错误

问题描述:

我有一个事件处理程序,例如,原生C++ 11事件 - 事件没事势必会引发错误

__event void MouseMoved(int MousePosX, int MousePosY); 

,并通过

__raise MouseMoved(MousePosX, MousePosY); 

这个工程使用__hook后完全没有上调给事件添加一个函数;然而,如果我提出即使绑定到事件的任何函数,我也会遇到运行时错误。在提升之前是否有办法检查事件是否为空?

+0

本地C++ 11没有__event。所以请标记并正确命名您的问题! – Klaus 2014-10-22 07:18:23

我选择只是定义我自己的事件对象,它包含可以按顺序调用的函数指针列表。如果函数与C#中的事件和事件处理程序非常相似。

struct EventArg 
{ 
public: 
    EventArg(){} 
    ~EventArg(){} 

    static EventArg Empty() 
    { 
     EventArg empty; 
     return empty; 
    } 
}; 


template <typename T> 
class EventHandler 
{ 
public: 
    EventHandler(void(T::*functionHandle)(void*, EventArg), T* receiver) 
    { 
     this->functionHandle = functionHandle; 
     this->receiver = receiver; 
    } 

    virtual void Call(void* sender, EventArg e) 
    { 
     (receiver->*functionHandle)(sender, e); 
    } 

private: 
    void (T::*functionHandle)(void*, EventArg); 
    T* receiver; 
}; 

class Event 
{ 
private: 
    std::vector<EventHandlerBase*> EventHandlers; 
public: 
    void Raise(void* sender, EventArgT e) 
    { 
     for (auto item = EventHandlers.begin(); item != EventHandlers.end(); item++) 
      (*item)->Call(sender, e); 
    } 

    void Add(EventHandler* functionHandle) 
    { 
     EventHandlers.push_back(functionHandle); 
    } 

    void Remove(EventHandler* functionHandle) 
    { 
     for (auto item = EventHandlers.begin(); item != EventHandlers.end(); item++) 
     { 
      if ((*item) == functionHandle) 
      { 
       EventHandlers.erase(item); 
       return; 
      } 
     } 
    } 
} 

C++ '11没有本地事件。 C++ '14也没有。

这对我来说是什么样的功能是特定于Microsoft Visual C++ - 也许Microsoft's Unified Event Model?如果是这样的话,举一个没有订阅者的事件不应该导致错误根据他们的文档:

要触发一个事件,只需调用声明为事件源类中的事件的方法。如果处理程序被挂钩,处理程序将被调用。

在另一方面,.NET需要您检查事件抚养他们和你使用同样在托管C++项目工作的这些关键字之前是空的,所以如果你创建了一个托管应用程序,它可以很好是你需要的,如果你想写可以移植的C++,关于其他的编译器和/或平台的工作做类似的东西

if(MouseMoved != nullptr) { 
    __raise MouseMoved(MousePosX, MousePosY); 
} 

,我可以推荐libsigc++JL Signal

+0

选中此:http://msdn.microsoft.com/en-us/library/ee2k0a7d.aspx – 2014-10-19 22:05:48

+0

这是我链接到Microsoft Visual C++特定编译器扩展的非常文章。关于空检查,它编译并在Visual C++ 2013 Express上运行:http://pastebin.com/KxStV0yy – Cygon 2014-10-19 22:09:02