rust-num / num-traits

Numeric traits for generic mathematics in Rust
Apache License 2.0
732 stars 135 forks source link

A trait to require ops on references #170

Closed vandenheuvel closed 4 years ago

vandenheuvel commented 4 years ago

I noticed e.g. this implementation to implement numerical operations on references, in this case impl<'a, 'b> Add<&'b BigInt> for &'a BigInt. Is there a trait that allows one to require that such implementations on references exist? E.g. something like below:

trait OpsOnBothValueAndRefs: NumOps<Self> + for<'r, 's> &'r Self: NumOps<'s Self> {}
cuviper commented 4 years ago

There are a few supertraits you can choose in various combinations of NumOps:

So you could write the full combination something like this:

trait OpsOnBothValueAndRefs: NumRef
where
    for<'r> &'r Self: RefNum<Self>,
{}

However, https://github.com/rust-lang/rust/issues/20671 is the reason such a trait isn't already provided. Since the extra where clause isn't elaborated, everywhere you write T: OpsOnBothValueAndRefs, you would also have to repeat the for<'r> &'r T: RefNum<T>, which loses a lot of the value of a combined trait in the first place.

vandenheuvel commented 4 years ago

That explains a lot. Thank you very much!