繁体   English   中英

如何使用 trait 制作泛型的泛型?

[英]How to make a generic of generic with trait?

pub struct Triangle<T: Float + std::clone::Clone, V: vector::Vector<T>> {
    point1: V,
    point2: V,
    point3: V,
}

这段代码无法编译,因为未使用 T(尽管如此,稍后在方法中使用了 T)

我试过这个语法

pub struct Triangle<V: vector::Vector<T: Float + std::clone::Clone>> {
    point1: V,
    point2: V,
    point3: V,
}

错误:

expected one of `!`, `(`, `+`, `,`, `::`, `<`, or `>`, found `:`

expected one of 7 possible tokens here

和这个语法

pub struct Triangle2<V> where V: vector::Vector<T> where T: Float {
    point1: V,
    point2: V,
    point3: V,
}

错误:

expected `where`, or `{` after struct name, found keyword `where`

expected `where`, or `{` after struct name

那行不通。

有没有办法解决这个问题?

我假设你的类型Vector看起来或多或少像这样。

pub trait Vector<T> {
    // Some functions
}

解决方案是声明多个泛型类型并分别列出它们的类型约束:类型V必须实现Vector<T>而类型T又必须实现FloatClone

pub struct Triangle<V, T>
where
    V: vector::Vector<T>,
    T: Float + Clone,
{
    point1: V,
    point2: V,
    point3: V,
    phantom: PhantomData<T>,
}

我正在使用std::marker::PhantomData来保存其他未使用的类型信息。

链接到完整的工作代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM