所以我有 usize 和 f32 的 const 钳位函数。逻辑很简单:它只是将
val
与 low
和 high
进行比较,然后返回范围内的合适值:
// you might have to switch up to nightly build:
// $ rustup default nightly
#![feature(const_trait_impl)]
#![feature(const_fn_floating_point_arithmetic)]
pub const fn usize_clamp(val: usize, low: usize, high: usize) -> usize {
if val < low {
return low;
}
if val > high {
return high;
}
return val;
}
pub const fn f32_clamp(val: f32, low: f32, high: f32) -> f32 {
if val < low {
return low;
}
if val > high {
return high;
}
return val;
}
现在我希望将它们合并为1:
pub const fn clamp<T: PartialOrd>(val: T, low: T, high: T) -> T {
if val < low {
return low;
}
if val > high {
return high;
}
return val;
}
编译器告诉我通过添加
T
来限制 ~const std::cmp::PartialOrd
的界限,所以我添加了它:
pub const fn clamp<T: PartialOrd + ~ const PartialOrd>(val: T, low: T, high: T) -> T {
if val < low {
return low;
}
if val > high {
return high;
}
return val;
}
然后它说
~const can only be applied to `#[const_trait]` traits
有人可以告诉我如何解决这个问题吗?
你不能。一般来说,通用
const
函数是一个不成熟的功能,预计在稳定之前会发生变化,目前还不清楚它的最终形状会是什么。