Created
February 5, 2016 21:32
-
-
Save Luthaf/084b40dfd369d24e200c to your computer and use it in GitHub Desktop.
Cloning Boxed trait objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait Potential { | |
fn energy(&self) -> f64; | |
} | |
// This is just a marker trait, to know which potentials can be used as pair | |
// potentials. I also have AnglePotential, GlobalPotential, ... | |
trait PairPotential: Potential {} | |
impl Clone for Box<PairPotential> { | |
fn clone(&self) -> Box<PairPotential> { | |
// What should I write here ? | |
unimplemented!() | |
} | |
} | |
// This is one way to to it, but I do not like it: too much boilerplate to write | |
// for all the 6 traits derived from Potential. Plus, I now use | |
// ClonablePotential in the library code, and the users must implement | |
// Potential, which render the API doc confusing. | |
/***************************************************************************/ | |
trait BoxClonePotential { | |
fn box_clone(&self) -> Box<ClonablePotential>; | |
} | |
impl<T: Clone + Potential + 'static> BoxClonePotential for T { | |
fn box_clone(&self) -> Box<ClonablePotential> { | |
Box::new(self.clone()) | |
} | |
} | |
trait ClonablePotential: Potential + BoxClonePotential {} | |
impl<T: Potential + BoxClonePotential> ClonablePotential for T {} | |
impl Clone for Box<ClonablePotential> { | |
fn clone(&self) -> Box<ClonablePotential> { | |
self.box_clone() | |
} | |
} | |
/***************************************************************************/ | |
#[derive(Clone)] struct A; | |
impl Potential for A { | |
fn energy(&self) -> f64 {56.0} | |
} | |
impl PairPotential for A {} | |
#[derive(Clone)] struct B; | |
impl Potential for B { | |
fn energy(&self) -> f64 {42.0} | |
} | |
impl PairPotential for B {} | |
fn main() { | |
let v: Vec<Box<PairPotential>> = vec![Box::new(A), Box::new(B)]; | |
for a in v.clone() { | |
println!("{:?}", a.energy()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment