[英]unconstrained type parameter error
我正在嘗試將glium與cgmath接口。 在這個答案之后 ,我實現了一個ToArray
特性,將cgmath::Matrix4
實例轉換為cgmath::Matrix4
可用的格式:
pub trait ToArray {
type Output;
fn to_array(&self) -> Self::Output;
}
impl<S: cgmath::BaseNum> ToArray for cgmath::Matrix4<S> {
type Output = [[S; 4]; 4];
fn to_array(&self) -> Self::Output {
(*self).into()
}
}
由於我並不總是直接使用Matrix4
,因此我需要一個類似於cgmath轉換類型的實現。 例如對於cgmath::Decomposed
:
impl<S: cgmath::BaseFloat, R: cgmath::Rotation3<S>> ToArray
for cgmath::Decomposed<cgmath::Vector3<S>, R> {
type Output = [[S; 4]; 4];
fn to_array(&self) -> Self::Output {
cgmath::Matrix4::<S>::from(*self).into()
}
}
這有效,但我想避免重復所有轉換類型的代碼,所以我想我會為可以轉換為Matrix4
任何東西定義一個通用實現:
impl<S: cgmath::BaseFloat, T: Into<cgmath::Matrix4<S>>> ToArray for T {
type Output = [[S; 4]; 4];
fn to_array(&self) -> Self::Output {
cgmath::Matrix4::<S>::from(*self).into()
}
}
不幸的是,這不起作用:
error[E0207]: the type parameter `S` is not constrained by the impl trait, self type, or predicates
--> src/main.rs:23:6
|
23 | impl<S: cgmath::BaseFloat, T: Into<cgmath::Matrix4<S>>> ToArray for T {
| ^ unconstrained type parameter
我有兩個問題:
rustc --explain
輸出,我希望T: Into<cgmath::Matrix4<S>>
作為S
和T
的有效約束。 Matrix4
任何東西編寫通用實現? 想象一下,我定義了這樣的類型1 :
struct PolymorphicMatrix;
impl Into<cgmath::Matrix4<f32>> for PolymorphicMatrix {
fn into(self) -> cgmath::Matrix4<f32> {
cgmath::Matrix4::new(
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0)
}
}
impl Into<cgmath::Matrix4<f64>> for PolymorphicMatrix {
fn into(self) -> cgmath::Matrix4<f64> {
cgmath::Matrix4::new(
2.0, 2.0, 2.0, 2.0,
2.0, 2.0, 2.0, 2.0,
2.0, 2.0, 2.0, 2.0,
2.0, 2.0, 2.0, 2.0)
}
}
哪些impls將用於實現ToArray
? 兩者都是適用的,但你只能實現ToArray
一次PolymorphicMatrix
,因為ToArray
無類型參數。 這就是錯誤的含義:它無效,因為它會在這種情況下導致問題。
由於您既不控制Into
也不控制cgmath::Matrix4
,您可以更改的唯一方面是ToArray
。 您可以添加特征定義本身未使用的類型參數,並且實現可以使用該類型參數。
pub trait ToArray<S> {
type Output;
fn to_array(&self) -> Self::Output;
}
impl<S: cgmath::BaseFloat, T: Into<cgmath::Matrix4<S>>> ToArray<S> for T {
type Output = [[S; 4]; 4];
fn to_array(&self) -> Self::Output {
cgmath::Matrix4::<S>::from(*self).into()
}
}
當然,您不能在S
和Output
之間強制執行任何類型的關聯。 此外,該類型參數可能會導致一些歧義:由於它沒有在特征中使用,編譯器可能無法在某些情況下從使用中推斷出S
,因此您可能必須明確指定它。 如果這成為問題,您可能想要使用generic-array
進行探索。 它可以讓你將數組維度提升為類型參數,這樣你就可以擺脫相關的類型,而是直接在to_array
的返回類型中使用類型參數,這將有助於編譯器的推理。
1通常,人們會實現From
而不是Into
。 我使用Into
這里說更貼近的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.