Jump to content
  • Advertisement
Sign in to follow this  
Lenolian

[.net] generic and arithmetic operators

This topic is 4868 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
Advertisement
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!