我目前正在实现一个射线追踪器,跟随着Jamis的“光线追踪挑战”一书。
我已经到了必须在矩阵上实现几个方法的部分,由于这些矩阵具有已知的编译时间,所以我选择使用const generics expressions (仍然只能在夜间通道上使用)来实现它们。
#![feature(generic_const_exprs)]Matrix类型定义如下:
#[derive(Debug)]
pub struct Matrix<const N: usize>(pub [[f64; N]; N]);我实现了以下方法:
impl<const N: usize> Matrix<N> {
fn submatrix(&self, index: Idx) -> Matrix<{ N - 1 }> {
//...
}
fn minor(&self, index: Idx) -> f64
where
[(); N - 1]:,
{
let submatrix = self.submatrix(index);
submatrix.determinant()
}
fn cofactor(&self, index: Idx) -> f64
where
[(); N - 1]:,
{
let minor = self.minor(index);
//...
}
fn determinant(&self) -> f64
where
[(); N - 1]:,
{
//...
}
}..。但是我遇到了submatrix方法的问题,它返回一个Matrix<{ N - 1 }>。
当对一个determinant方法调用submatrix方法时,这就是我们在minor方法中所做的:
fn minor(&self, index: Idx) -> f64
where
[(); N - 1]:,
{
let submatrix: Matrix<{ N - 1 }> = self.submatrix(index);
submatrix.determinant()
}..。即使minor方法受到以下约束的限制:
where [(); N - 1]:,..。编译器仍然会抱怨并建议添加相同的where bound using this expression。
error: unconstrained generic constant
--> src/rt/matrix.rs:109:19
|
109 | submatrix.determinant()
| ^^^^^^^^^^^
|
= help: try adding a `where` bound using this expression: `where [(); N - 1]:`
note: required by a bound in `Matrix::<N>::determinant`
--> src/rt/matrix.rs:128:14
|
126 | fn determinant(&self) -> f64
| ----------- required by a bound in this
127 | where
128 | [(); N - 1]:,
| ^^^^^ required by this bound in `Matrix::<N>::determinant`我试图为minor实现Matrix<{ N - 1 }>方法,但它似乎也不起作用(更确切地说,我不知道如何做到这一点,或者如果可能的话):
impl<const N: usize> Matrix<{ N - 1 }> {
fn minor(&self, index: Idx) -> f64 {
let submatrix = self.submatrix(index);
submatrix.determinant()
}..。这将产生以下错误:
error[E0207]: the const parameter `N` is not constrained by the impl trait, self type, or predicates
--> src/rt/matrix.rs:138:12
|
138 | impl<const N: usize> Matrix<{ N - 1 }> {
| ^ unconstrained const parameter
|
= note: expressions using a const parameter must map each value to a distinct output value
= note: proving the result of expressions other than the parameter are unique is not supported我想知道我在这里试图用submatrix做什么是可能的。这不是什么大问题,因为我可以为每个可能的N定义这些方法,在我的例子中,这些方法仅限于2_usize、3_usize和4_usize,但是只为Matrix<N>实现这些方法将更加简洁!
发布于 2022-02-20 01:23:21
警告:,generic_const_exprs功能非常不稳定!不要在生产中使用它!
您可以在determinant()上调用submatrix,它已经是Matrix<{ N - 1 }> (从submatrix()返回)。因此,您也可以将其限制为where [(); N - 1 - 1]:, (请注意,Rust编译器不够聪明,无法理解这与where [(); N - 2]:,相同,也不能得出结论,如果这也适用于where [(); N - 1]:,。您必须同时编写:where [(); N - 1]:, [(); N - 1 - 1]:,):
fn minor(&self, index: Idx) -> f64
where
[(); N - 1]:,
[(); N - 1 - 1]:,
{
let submatrix = self.submatrix(index);
submatrix.determinant()
}
fn cofactor(&self, index: Idx) -> f64
where
[(); N - 1]:,
[(); N - 1 - 1]:,
{
let minor = self.minor(index);
//...
}https://stackoverflow.com/questions/71185365
复制相似问题