6

我正在尝试将 glium 与 cgmath 接口。在这个答案之后,我实现了一个ToArray特性来将实例转换cgmath::Matrix4为 glium 可用的格式:

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>>的有效约束。ST
  • 我如何为可以转换为的任何东西编写通用实现Matrix4
4

1 回答 1

6

想象一下,我定义了一个像这样的类型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一次 for PolymorphicMatrix,因为ToArray没有类型参数。这就是错误的含义:它无效,因为它会在这种情况下导致问题。

由于您既不控制Into也不控制cgmath::Matrix4,因此您可以改变的唯一方面是ToArray。您可以添加一个未在 trait 定义本身中使用的类型参数,并且实现可以使用该类型参数。

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()
    }
}

自然,您不能在 和 之间强制执行任何类型的相关SOutput。此外,该类型参数可能会导致一些歧义:由于它没有在 trait 中使用,编译器在某些情况下可能无法S从用法推断,因此您可能必须明确指定它。如果这成为问题,您可能想探索使用generic-array. 它可以让你将数组维度提升为类型参数,这样你就可以摆脱关联的类型,而是直接在返回类型中使用类型参数to_array,这将有助于编译器的推断。


1通常,人们会实施From而不是Into. 我在Into这里使用是为了更接近所述问题。

于 2017-05-13T11:22:35.203 回答