Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::any::{Any, TypeId};
- use std::collections::HashMap;
- struct Fabrica {
- constructors: HashMap<TypeId, Box<Fn() -> Box<Any>>>,
- }
- impl Fabrica {
- fn new() -> Self {
- Fabrica {
- constructors: HashMap::new(),
- }
- }
- fn register<F: 'static, T: Any>(&mut self, func: F)
- where
- F: Fn() -> T,
- {
- let type_id = TypeId::of::<T>();
- let constructor = Box::new(move || Box::new(func()) as Box<Any>);
- assert!(self.constructors.insert(type_id, constructor).is_none())
- }
- fn create<T: Any>(&self) -> Option<T> {
- self.constructors
- .get(&TypeId::of::<T>())
- .map(|func| *func().downcast::<T>().unwrap())
- }
- }
- fn main() {
- let mut f = Fabrica::new();
- f.register(|| 1u32);
- println!("{}", f.create::<u32>().unwrap());
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement