Trait ref_ops::RefAdd[][src]

pub trait RefAdd<Rhs>: Add<Rhs> {
    fn ref_add(&self, other: Rhs) -> Self::Output;
}
Expand description

An escape hatch for implimenting Add for references to newtypes.

As of Rust 1.52.1, the following code does not compile:

use core::ops::Add;

#[derive(PartialEq)]
struct A<T>(T);

impl<'a, 'b, T, U> Add<&'b A<U>> for &'a A<T>
where
    T: Add<&'b U>,
    &'a T: Add<&'b U, Output = T::Output>,
{
    type Output = A<T::Output>;

    fn add(self, other: &'b A<U>) -> Self::Output {
        A(self.0.add(&other.0))
    }
}

pub fn f<T, U>(a: T, b: U)
where
    for<'a, 'b> &'a T: Add<&'b U>,
{
    let a_b = (&a).add(&b);

    // to do something with `a`, `b`, and `a_b`
    todo!();
}

pub fn g<T, U>(a: T, b: U)
where
    for<'a, 'b> &'a T: Add<&'b U>,
{
    f(a, b);
}

assert!(&A(1.0) + &A(2.0) == A(3.0));

but the following code does:

use core::ops::Add;
use ref_ops::RefAdd;

#[derive(PartialEq)]
struct A<T>(T);

impl<'a, T, U> Add<&'a A<U>> for &A<T>
where
    T: RefAdd<&'a U>,
{
    type Output = A<T::Output>;

    fn add(self, other: &'a A<U>) -> Self::Output {
        A(self.0.ref_add(&other.0))
    }
}

pub fn f<T, U>(a: T, b: U)
where
    for<'a, 'b> &'a T: Add<&'b U>,
{
    let a_b = (&a).add(&b);

    // to do something with `a`, `b`, and `a_b`
    todo!();
}

pub fn g<T, U>(a: T, b: U)
where
    for<'a, 'b> &'a T: Add<&'b U>,
{
    f(a, b);
}

assert!(&A(1.0) + &A(2.0) == A(3.0));

Required methods

Implementors