我有一個帶有兩個通用typenum
參數的impl。當參數相同時,impl的函數應該返回一個不同的類型。 (不同的類型是一個更緊湊的表示,只能在類型參數相同時才能實現)。是否可以使用基於類型相等的不同impl?下面的天真方法會產生一個「衝突的實現」錯誤,因爲Rust沒有采用更具體的實現。當類型參數相同時使用不同的impl
extern crate typenum;
use typenum::Unsigned;
use std::ops::Mul;
use std::marker::PhantomData;
struct Matrix<N: Unsigned, M: Unsigned> {
n: usize,
m: usize,
elements: Vec<f64>,
_marker: PhantomData<(N, M)>
}
// The more compact representation
struct SquareMatrix<N: Unsigned> {
n: usize,
elements: Vec<f64>,
_marker: PhantomData<(N)>
}
impl<N: Unsigned, D: Unsigned, M: Unsigned> Mul<Matrix<D, M>> for Matrix<N, D> {
type Output = Matrix<N, M>;
fn mul(self, rhs: Matrix<D, M>) -> Self::Output {
unimplemented!()
}
}
// The more specific implementation
impl<N: Unsigned, D: Unsigned> Mul<Matrix<D, N>> for Matrix<N, D> {
type Output = SquareMatrix<N>;
fn mul(self, rhs: Matrix<D, N>) -> Self::Output {
unimplemented!()
}
}
在Rust特徵門後面找不到好東西。 – drhagen
我在哪裏可以找到「專業化」的文檔?它沒有列出[這裏](https://doc.rust-lang.org/nightly/reference/attributes.html#compiler-features)或[here](https://doc.rust-lang.org/reference。 HTML#編譯器的功能);是否有其他地方我應該查看可用/可能的'功能'列表? – ildjarn
目前關於專業化的最佳文檔可能是我鏈接到的RFC。缺乏新功能的文檔是[已知問題](https://github.com/rust-lang/rfcs/blob/master/text/1636-document_all_features.md)。可用編譯器功能的詳盡列表可能只存在於編譯器的源代碼中。 –