0

示例:给定以下特征,

trait DirectedAcyclicGraph<V, E> where V: Add, E: Add

我希望每当一个类型的值与返回V另一个类型的值相同类型的值时V。每当将一个类型的值E添加到另一个相同类型的值时,我都希望E返回另一个值。

天真地,我认为这可能是正确的方向,

trait DirectedAcyclicGraph<V, E> where V: Add<Output = V>, E: Add<Output = E>

但这只是在黑暗中拍摄的。

Add提供以下示例的文档,

use std::ops::Add;

struct Foo;

impl Add for Foo {
    type Output = Foo;

    fn add(self, _rhs: Foo) -> Foo {
        println!("Adding!");
        self
    }
}

fn main() {
    Foo + Foo;
}

但我无法理解如何以同样的方式为泛型类型提供实现,如果这是可能的话。

4

1 回答 1

0

这最终是一个编程错误的情况。正如@ChrisMorgan在他的示例中指出的那样,表达式Add<Output = V>确实可以编译。编译器哭泣的原因是在生产源代码的一个位置Output = V没有被一致地添加。

遗憾的是,我在编译精简的 MWE 时也一定犯了一些错误。

因此,后代的收获是

trait DirectedAcyclicGraph<V, E> where V: Add<Output = V>, E: Add<Output = E>

作品。

于 2016-03-12T20:46:33.987 回答