I have a trait like this:
use std::ops::Add;
pub trait GroupElement: Clone + Sized {
fn plus(&self, b: &Self) -> Self;
}
#[derive(Debug)]
struct G1 {
value: i32,
}
#[derive(Debug)]
struct G2 {
value: i32,
}
impl GroupElement for G1 {
fn plus(&self, b: &Self) -> Self {
let value = self.value + b.value;
G1 { value }
}
}
impl GroupElement for G2 {
fn plus(&self, b: &Self) -> Self {
let value = self.value + b.value;
G2 { value }
}
}
Now if I wanted to overload the +
operator without code duplication I could use a macro to implement the Add
trait like this
impl Add for $group_element {
type Output = Self;
fn add(self, other: Self) -> Self {
self.plus(&other)
}
}
But I want to implement Add
for the trait GroupElement
so that I can use the generic functions over GroupElement
by using the +
operator.
impl<T: GroupElement> Add<T> for GroupElement {
type Output = Self;
fn add(self, other: T) -> Self {
self.plus(&other)
}
}
Above code comlains about GroupElement not having a known size at compile time which I agree with, different groups will have different sizes.
I tried the following code
impl<T: GroupElement> Add<T> for T {
type Output = T;
fn add(self, other: T) -> T {
self.plus(&other)
}
}
I get error with message type parameter `T` must be used as the type parameter for some local type
which seems incorrect since GroupElement
is local to my crate.
How should I solve this? The actual implementation of GroupElement is here. Links to G1 and G2.