Redefine trait for infix operators

138 views Asked by At

I'm trying to redefine the Add trait so that I could use it as infix operator:

//use std::ops::Add;

trait Add<RHS=Self> {
    // type Output;

    fn add(self, rhs: RHS) -> Self;
}

fn summ<T: Add>(a: T, b: T) -> T {  
    a+b
}  // doesn't compile 

Is it possible to redefine the Add trait so that it will use the + operator for add functionality?

1

There are 1 answers

1
Shepmaster On BEST ANSWER

It is not possible to redefine any traits. You could create your own trait with the same name and same methods, which is what you have done. However, the operator + is tied to std::ops::Add, so it wouldn't be useful in this case.

In your case, it looks like you just want to specify Add::Output to return a T:

use std::ops::Add;

fn summ<T>(a: T, b: T) -> T
    where T: Add<Output = T>
{  
    a + b
}