Advertisement
Guest User

Untitled

a guest
Apr 19th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. use std::any::{Any, TypeId};
  2. use std::collections::HashMap;
  3. struct Fabrica {
  4. constructors: HashMap<TypeId, Box<Fn() -> Box<Any>>>,
  5. }
  6. impl Fabrica {
  7. fn new() -> Self {
  8. Fabrica {
  9. constructors: HashMap::new(),
  10. }
  11. }
  12. fn register<F: 'static, T: Any>(&mut self, func: F)
  13. where
  14. F: Fn() -> T,
  15. {
  16. let type_id = TypeId::of::<T>();
  17. let constructor = Box::new(move || Box::new(func()) as Box<Any>);
  18.  
  19. assert!(self.constructors.insert(type_id, constructor).is_none())
  20. }
  21.  
  22. fn create<T: Any>(&self) -> Option<T> {
  23. self.constructors
  24. .get(&TypeId::of::<T>())
  25. .map(|func| *func().downcast::<T>().unwrap())
  26. }
  27. }
  28.  
  29. fn main() {
  30. let mut f = Fabrica::new();
  31. f.register(|| 1u32);
  32. println!("{}", f.create::<u32>().unwrap());
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement