Hello everyone
I have a question I can't find an aswer searching this forum
I want to create a Matrix
trait that allows me to use generic types behaving like matrices. So I can use it like this:
fn do_some<T: Float, M: Matrix<T,R,C>>() -> M {
M::identity() * M::one() // whatever
}
generic trait method
When the matrices operators are trait methods, everything works well. But the result is not convenient to use: no syntaxic operators.
The add method below defines that "types implenting Matrix<T,R,C> can sum to every other implementor of Matrix<T,R,C>"
pub trait Matrix<T, R, C>:
Clone
+ Index<[usize; 2], Output=T>
{
type Owned<R2, C2>: Matrix<T,R2,C2> + Default;
fn matadd<M>(self, other: M) -> Self::Owned<R,C>
where M: Matrix<T,R,C>;
}
generic super-trait bound
I want to move the add operator requirement to the super trait, so it can be the syntaxic Add
operator
What I want is the following, however the compiler complains Add
bound must be a concrete type
pub trait Matrix<T, R, C>:
Clone
+ Index<[usize; 2], Output=T>
+ Add<impl Matrix<T,R,C>, Output=Self::Owned<R,C>> // this
// + Add<Matrix<T,R,C>, Output=Self::Owned<R,C>> // or this
{
type Owned<R2, C2>: Matrix<T,R2,C2> + Default;
}
super-trait bound using trait arguments
I could give it a concrete type with generics, but this wouldn't give the same:
With the code below:
- it means "types implementing Matrix<T,R,C> can sum to an other specific implementation of Matrix<T,R,C>"
- rather than
"types implenting Matrix<T,R,C> can sum to every other implementor of Matrix<T,R,C>"
pub trait Matrix<T, R, C, M>: // adding a trait argument
Clone
+ Index<[usize; 2], Output=T>
+ Add<M, Output=Self::Owned<R,C>> // this is accepted but doesn't mean M is generic
where M: Matrix<T,R,C>
{
type Owned<R2, C2>: Matrix<T,R2,C2> + Default;
}
So what I want is the same as a generic method in a trait, but for a super trait bound. Is there a way to acheive this ?
edit: I do not want to use a Add<dyn Trait>
bound instead, because dynamic dispatch of methods leads to poor performances when called as often as a matrix or vector product. It prevents the compiler from inlining and optimizing the operation