我正在尝试创建一个函数,它可以接受一个带有引用的lambda和一个接受一个值的lambda。
一个例子可能会有帮助,因为它很难描述。
fn derivative<F, R>(f: &F, x: f64) -> R
where F: Fn(f64) -> R,
R: Div<f64, Output=R> + Sub<Output=R>
{
let epsilon = 1e-7;
(f(x + epsilon / 2.0) - f(x - epsilon / 2.0)) / epsilon
}
fn derivative<F, R>(f: &F, x: f64) -> R
where F: Fn(&f64) -> R,
R: Div<f64, Output=R> + Sub<Output=R>
{
let epsilon: f64 = 1e-7;
(f(&(x + epsilon / 2.0)) - f(&(x - epsilon / 2.0))) / epsilon
}这个函数近似于f的导数,我想同时支持Fn<f64>和Fn<&f64>。在C++中,我会执行部分模板专门化(只是模式匹配模板参数的一个花哨术语),在锈蚀中有类似的东西吗?
我认为语法看起来像示例代码,但显然编译器告诉我derivative已经被重新定义了E4028。
或者有更简单的方法来实现这种行为?
发布于 2022-06-29 22:46:46
最近我遇到了一个类似的问题,我想专门研究一种基于类型参数的方法。下面是一个独立的例子,似乎很有效:
// trait is specialized for each specialization
pub trait SomeTraitSpecification<T> {
fn someFunctionImpl(&self, value: T);
}
// base trait
struct SomeStructure;
impl SomeStructure {
// function entry
// where clause restricts function options down to specific specialization function
pub fn someFunction<T>(&self, value: T) where Self: SomeTraitSpecification<T> {
// does nothing but call the specialized function
self.someFunctionImpl(value);
}
}
// implement SomeTraitSpecification for each type you want to call SomeStructure on
// declared in different impl blocks to avoid redefinitions
// f32 specialization
impl SomeTraitSpecification<f32> for SomeStructure {
fn someFunctionImpl(&self, value: f32) {
println!("float!");
}
}
// i32 specialization
impl SomeTraitSpecification<i32> for SomeStructure {
fn someFunctionImpl(&self, value: i32) {
println!("integer!")
}
}
fn main() {
let structure = SomeStructure {};
structure.someFunction(4); // calls i32 specialization
structure.someFunction(5.0); // calls f32 specialization
}虽然有点冗长,但确实有效。SomeTraitSpecialization特性用于提供专门化。someFunction<T>上的" where“子句就是魔术发生的地方--我提供了一些注释,添加了一些说明。希望您可以将其修改为有用的。
https://stackoverflow.com/questions/72807691
复制相似问题