[.net] generic and arithmetic operators

Started by
1 comment, last by Lenolian 18 years, 9 months ago
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.
Advertisement
This is once of the major drawbacks for generics in .NET. There have been attempts to work around this, such as this.
"Voilà! In view, a humble vaudevillian veteran, cast vicariously as both victim and villain by the vicissitudes of Fate. This visage, no mere veneer of vanity, is a vestige of the vox populi, now vacant, vanished. However, this valorous visitation of a bygone vexation stands vivified, and has vowed to vanquish these venal and virulent vermin vanguarding vice and vouchsafing the violently vicious and voracious violation of volition. The only verdict is vengeance; a vendetta held as a votive, not in vain, for the value and veracity of such shall one day vindicate the vigilant and the virtuous. Verily, this vichyssoise of verbiage veers most verbose, so let me simply add that it's my very good honor to meet you and you may call me V.".....V
Thanks for the link.

Doing it in generic implies too much construction to be done. I want to keep it simple, so i will stick with adding overloads until something better get out.

This topic is closed to new replies.

Advertisement