I am currently coding some maths functions and have some problems with generic and arithmetic operations.
For example, now i have a class that make interpolation like this
public sealed class LinearInterpolator
{
public static float Interpolate(float a, float b, float x)
{
return (a + ( (b-a) * x) );
}
public static Vector2 Interpolate(Vector2 a, Vector2 b, float x)
{
return (a + ( (b-a) * x) );
}
public static Vector2 Interpolate(Vector2 a, Vector2 b, float x)
{
return (a + ( (b-a) * x) );
}
// more overloads
}
So i thought it would be a good candidate for generic as that would make easier to add new types later. So i did :
public sealed class LinearInterpolator<T>
{
public static T Interpolate(T a, T b, float x)
{
return (a + ( (b-a) * x) );
}
}
The problem is that it doesnt compile since there is no constraint to allow arithmetic operators. And i am stuck here, i tried to make an interface to allow arithmetic operations :
public interface IInterpolable<T>
{
T Add(T a, T b);
T Subtract(T a, T b);
T Mulitply(T a, float x);
}
This works well for my own type but then i cant use int, float...
Anyone as a suggestion on how to do it ?
It would be perfect if you were allowed to add constraint about operators, something like :
class Foo<T> where T : T+(T,T) // allow operator + to be used in generic.