pub trait RefAdd<Rhs> {
    type Output;

    fn ref_add(&self, rhs: Rhs) -> Self::Output;
}
Expand description

An escape hatch for implimenting Add for references to structs.

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

use as_is::ToOwned;
use core::ops::Add;

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

impl<'a, 'b, T: ?Sized + ToOwned, U, O> Add<&'b A<U>> for &'a A<T>
where
    T::Owned: Add<&'b U, Output = O>,
    &'a T: Add<&'b U, Output = O>,
{
    type Output = A<O>;

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

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

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

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 as_is::ToOwned;
use as_is::ref_ops::RefAdd;
use core::ops::Add;

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

impl<'a, T: ?Sized + ToOwned, U, O> Add<&'a A<U>> for &A<T>
where
    T::Owned: Add<&'a U, Output = O>,
    T: RefAdd<&'a U, Output = O>,
{
    type Output = A<O>;

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

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

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

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 Associated Types

Required Methods

Implementors