<Self>这是我以前一个问题的“续集”,其中有一个更具代表性的例子,并且通过公认的答案告知了另一种方法。 当前代码状态: 操场链接 repo/branch lin ...

问题描述 投票:0回答:0

游戏链接

rrepo/分支链接

    我的lib板条箱在多个维度和插值策略上提供了数值插值。可以在实例化后证明不同的thime(动态派遣)时更改
  • 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

,而是定义一个新结构来保存相关数据并传递该问题。
	

rust dynamic-dispatch
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.