Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #![feature(core_intrinsics)]
- fn main() {
- let mut e = EventManager::default();
- e.add_listener(&foo);
- }
- trait IEventData {
- fn get_timestamp(&self) -> std::time::Duration;
- fn get_name() -> &'static str where Self: Sized;
- }
- trait IEventManager<'a> {
- fn add_listener<E, F>(&mut self, f: F) where E: 'static + IEventData + Sized, F: 'a + FnMut(&E);
- }
- struct Event;
- impl IEventData for Event {
- fn get_timestamp(&self) -> std::time::Duration {
- std::time::Duration::from_millis(0)
- }
- fn get_name() -> &'static str {
- unsafe { std::intrinsics::type_name::<Self>() }
- }
- }
- fn foo(e: &Event) {}
- #[derive(Default)]
- struct EventManager<'a> {
- events: std::collections::VecDeque<Box<dyn IEventData>>,
- listeners: std::collections::HashMap<&'static str, Box<FnMut(&dyn std::any::Any) + 'a>>
- }
- impl<'a> IEventManager<'a> for EventManager<'a> {
- fn add_listener<E, F>(&mut self, mut f: F) where E: 'static + IEventData + Sized, F: 'a + FnMut(&E) {
- let name = E::get_name();
- self.listeners.insert(name, Box::new(move |e| f(e.downcast_ref::<E>().unwrap())));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement