C
C#14mo ago
triplemocha

❔ operator * cannot be applied to operands of type T and T

I'm getting this error: operator * cannot be applied to operands of type T and T I understand why, but I'm wondering if there's a way to add a constraint only to ints , floats and doubles. Sounds like it's a no. What else can be done?
struct Vector2D<T>
{
public T x, y;

public Vector2D()
{
x = y = default(T);
}

public Vector2D(T xPos, T yPos)
{
x = xPos;
y = yPos;
}

public T GetMagnitude()
{
return System.Math.Sqrt(x * x + y * y); // error
}
}
struct Vector2D<T>
{
public T x, y;

public Vector2D()
{
x = y = default(T);
}

public Vector2D(T xPos, T yPos)
{
x = xPos;
y = yPos;
}

public T GetMagnitude()
{
return System.Math.Sqrt(x * x + y * y); // error
}
}
7 Replies
Jimmacle
Jimmacle14mo ago
if you're using .NET 7 you can constrain T to IMultiplyOperators<T,T,T> or more generally INumber<T> it doesn't specifically constrain to those 3 types, but it will allow you to do math on whatever T is note that Math.Sqrt expects a double and you'll have to convert the result of your math to a double explicitly using double.CreateChecked<T>(T value) same for converting back to T (T.CreateChecked) because it returns a double so you'd end up with something like
struct Vector2D<T> where T : INumber<T>
{
public T x, y;

public Vector2D()
{
x = y = default(T);
}

public Vector2D(T xPos, T yPos)
{
x = xPos;
y = yPos;
}

public T GetMagnitude()
{
return T.CreateChecked(System.Math.Sqrt(double.CreateChecked(x * x + y * y)));
}
}
struct Vector2D<T> where T : INumber<T>
{
public T x, y;

public Vector2D()
{
x = y = default(T);
}

public Vector2D(T xPos, T yPos)
{
x = xPos;
y = yPos;
}

public T GetMagnitude()
{
return T.CreateChecked(System.Math.Sqrt(double.CreateChecked(x * x + y * y)));
}
}
i will say i've attempted to write a generic 3D math library before and the generic math gets kind of annoying to handle once you get to vectorizing things
triplemocha
triplemocha14mo ago
This seems to be working. Thanks. Yeah, I think it's probably best to avoid generics in this case. Probably not the fastest for games in general, since it's doing extra work in the background to get the magnitude here.
Jimmacle
Jimmacle14mo ago
if you're using Math.Sqrt it will be converting to and from double regardless, just maybe implicitly you could benchmark both solutions but i wouldn't expect a big difference if any
triplemocha
triplemocha14mo ago
I'll be using Unity shortly, so I'll just use what it has. Mine is just a simple class for testing a few things beforehand.
Jimmacle
Jimmacle14mo ago
oh if you're in unity you can't use this anyway at least i don't think they have any support for generic math, it only came in the latest .NET version and unity... does not have it
triplemocha
triplemocha14mo ago
Okay.
Accord
Accord14mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.