繁体   English   中英

您如何以 rust 方式实现 EventDispatcher?

[英]how do you implement an EventDispatcher the rust way?

所以我一直在尝试使用 rust 创建一个渲染引擎,并且我一直基于一些 C++ 代码做同样的事情。 而且我被困在你如何以生锈的方式编写事件调度程序。 这是 C++ 代码

class EventDispatcher {
    template<typename T>
    using EventFn = std::function<bool(T&)>;
public:
    EventDispatcher(Event& event) : m_Event(event) {}

    template<typename T>
    bool Dispatch(EventFn<T> func) {
        if (m_Event.GetEventType() == T::GetStaticType()) {
            m_Event.m_Handeled = func(*(T*)&m_Event);
            return true;
        }
        return false;
    }
private:
    Event& m_Event;
};

它会像这样使用

void SomeOtherClass::OnEvent(Event& e) {
    EventDispatcher dispatcher(e);
    dispatcher.Dispatch<RandomEvent>(std::bind(&Application::EventHandler, this, std::placeholders::_1));
}

我试图在 rust 中实现类似的模式,这就是我到目前为止所得到的

pub struct EventDispatcher<T: EventTrait> {
    event: Box<T>,
}

impl<T: EventTrait> EventDispatcher<T> {
    pub fn dispatch<V: EventTrait>(&mut self, func: impl Fn(&mut V) -> bool) -> bool {
        if self.event.type_id() == TypeId::of::<V>() {
            let res = func(unsafe { &mut *(self.event as *mut T as *mut V) });
            self.event.set_is_handeled(res);
            return res;
        } else {
            false
        }
    }
}

我很确定这是非常错误的,我仍在尝试学习 rust。 任何帮助将不胜感激::D

好吧,我认为我目前的方法不是最好的,我尝试为这个问题实现观察者模式,我觉得它更合适!

pub trait IObserver {
    fn update(&self, event: &impl EventTrait);
}

pub trait ISubject<'a, T: IObserver> {
    fn attach(&mut self, observer: &'a T);
    fn detach(&mut self, observer: &'a T);
    fn notify(&self, event: &impl EventTrait);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM