Is it possible to inherit a trait where Self is only a type parameter of the trait?

时间:2017-04-06 17:18:19

标签: inheritance rust traits

I want to require that implementing trait A requires that f64 implements Add<Self, Output = Self>. One may call this reverse trait inheritance.

I could use a where clause for this, but this has the downside that every time I want to use the trait I have to add this condition in the where clause of the function.

I've added a simple example below to illustrate the problem. The condition I would like to remove is marked with a comment. You can find it as a playground here.

use std::ops::Add;

#[derive(Copy, Clone, Debug)]
struct Num(f64);

impl Add for Num {
    type Output = Num;
    fn add(self, rhs: Num) -> Self::Output {
        Num(self.0 + rhs.0)
    }
}

impl Add<f64> for Num {
    type Output = Num;
    fn add(self, rhs: f64) -> Self::Output {
        Num(self.0 + rhs)
    }
}

impl Add<Num> for f64 {
    type Output = Num;
    fn add(self, rhs: Num) -> Self::Output {
        Num(self + rhs.0)
    }
}

trait AddF64 : Add<Output=Self> + Add<f64, Output=Self> + Copy
    where f64: Add<Self, Output=Self>,
{}

impl<T> AddF64 for T
where
    T: Add<Output=T> + Add<f64, Output=T> + Copy,
    f64: Add<T, Output=T>
{}

fn foo<T: AddF64>(x: T, y: T) -> T
where f64: Add<T, Output=T> // I would like to remove this line!
{
    1.0 + x + y
}

fn main() {
    let n = Num(1.0);
    let res = foo(n, n);
    println!("{:?}", &res);
}

I'm pretty sure that this question should have been asked already, but I've found nothing.

0 个答案:

没有答案