Interp1D
实例的策略。
Box<dyn Strategy1D>
我想支持
静态调度以允许更好的运行时性能,同时仍然允许用户在运行时切换策略。
这意味着我的结构将对该策略有一个通用,以支持静态调度:
pub struct Interp1D {
x: Vec<f64>,
f_x: Vec<f64>,
strategy: Box<dyn Strategy1D>,
}
pub trait Strategy1D {
fn interpolate(
&self,
interpolator: &Interp1D,
point: &[f64; 1],
) -> f64;
}
添加此内容:Box<dyn Strategy1D>
使编译器疯狂,pub struct Interp1D<S: Strategy1D> {
x: Vec<f64>,
f_x: Vec<f64>,
strategy: S,
}
// as a consequence the trait needs to change:
pub trait Strategy1D: Sized { // the `Sized` bound here makes this dyn-incompatible
fn interpolate(
&self,
interpolator: &Interp1D<Self>, // the `Self` here requires `Sized`
point: &[f64; 1],
) -> f64;
}
impl Strategy1D for Box<dyn Strategy1D> {
// ^^^^^^^^^^^^^^^^^^^
// error[E0038]: the trait `Strategy1D` cannot be made into an object
fn interpolate(
&self,
interpolator: &Interp1D<Self>,
point: &[f64; 1],
) -> f64 {
// delegate to boxed thing
(**self).interpolate(struct, interpolator, point)
}
}
界不兼容。
有某种方法使特质dyn兼容吗?还是不可能,如果我想允许动态调度,我应该坚持原始代码吗?
i我能够通过更改性状方法来不采用
Strategy1D