2

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
wiep
  • 172
  • 1
  • 7
  • I think you need to either wait for [trait alias](https://github.com/rust-lang/rfcs/pull/1733) or [implicit bounds](https://internals.rust-lang.org/t/lang-team-minutes-implied-bounds/4905) to land to remove that line. – kennytm Apr 07 '17 at 00:34
  • @kennytm thanks for the hint. i'll track the progress on both features. – wiep Apr 10 '17 at 09:35

0 Answers0