微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C:如何在没有void指针的情况下构建事件/消息系统?

我希望在我的C项目中有一个动态消息传递系统,其中有一个固定的现有事件列表,事件可以在运行时的任何地方触发,以及在哪里可以为某些事件订阅回调函数.

在这些事件中传递的参数应该有一个选项.例如,一个事件可能不需要任何参数(EVENT_EXIT),有些可能需要多个参数(EVENT_PLAYER_CHAT:播放器对象指针,带消息的字符串)

使这成为可能的第一个选项是允许在触发事件时将void指针作为参数传递给事件管理器,并在回调函数中接收它.

虽然:我被告知无效指针是不安全的,我不应该使用它们.

>如何在不使用void指针的情况下保持(半)动态参数类型和事件计数?

解决方法

您可以使用基类,可选择抽象,并使用dynamic_cast.该参数将在运行时检查.但编译时可能会更好.
class EventArgs
{
public:
   virtual ~EventArgs();
};

class PlayerChatEventArgs : public EventArgs
{
public:
   PlayerChatEventArgs(Player* player,const std::string& message);
   virtual ~PlayerChatEventArgs();
   Player* GetPlayer() const;
   const std::string& GetMessage() const;
private:
   Player* player;
   std::string message;
};

class Event
{
public:
   virtual ~Event() = 0;
   virtual void Handle(const EventArgs& args) = 0;
};

class ExitEvent : public Event
{
public:
   virtual ~ExitEvent();
   virtual void Handle(const EventArgs& /*args*/)
   {
      // Perform exit stuff.
   }
};

class PlayerChatEvent : public Event
{
public:
   virtual ~PlayerChatEvent();
   virtual void Handle(const EventArgs& args)
   {
      // this will throw a bad_cast exception if cast fails.
      const PlayerChatEventArgs& playerchatargs =
         dynamic_cast<const PlayerChatEventArgs&>(args);
      // Perform player chat stuff.
   }
};

原文地址:https://www.jb51.cc/c/115126.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐