❔ 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?
7 Replies
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
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 thingsThis 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.
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
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.
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
Okay.
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.