Suppose you are writing a class for a generic vector and you want to naively implement a method to add two vectors:
This won’t work. The compiler is unable to interpret the “+” for type T so v1.x + v2.x cannot be compiled.
One of possible approaches could be to restrict possible Ts with a type constraint so that “+” can be replaced with a method of an interface implemented by T. Such approach, however, does not take you anywhere since you cannot impose an interface on an existing type and thus, Vec<int> or Vec<double> would still fail to compile.
Another common approach is to define an auxiliary interface:
so that Vec::Add can be now implemented as:
While this works, there are obvious drawbacks – an extra implementation of the auxiliary interface has to be provided for any T you want to use your Vec class with. Also, the signature of the Add method is now rather clumsy.
Let’s then just start again: