How to do math operations with generic function arguments?
-
T will be some value type int, float, double, etc... public T Mean(T[] vec) where T : ??????? { T tmp = 0; <--- error foreach (T v in vec) tmp += v; <--- error return tmp / vec.Length; <--- error } Are they so complex compared to C++
chesnokov
-
T will be some value type int, float, double, etc... public T Mean(T[] vec) where T : ??????? { T tmp = 0; <--- error foreach (T v in vec) tmp += v; <--- error return tmp / vec.Length; <--- error } Are they so complex compared to C++
chesnokov
Sad but true: there is (not yet) a INumber or IArithmetic interface for this. So either you have to use reflection to query the operators or you have to define a Interface yourself. With .net 3.5 you can use the extension-method system to add the implementation for your interface to double/int/etc. so maybe this is the best way.
-
T will be some value type int, float, double, etc... public T Mean(T[] vec) where T : ??????? { T tmp = 0; <--- error foreach (T v in vec) tmp += v; <--- error return tmp / vec.Length; <--- error } Are they so complex compared to C++
chesnokov
try this :
public T Mean(T[] vec) where T : Int32,Double,Fload,..... { tmp = default(T); //Return the default for each Primitive, for No primitive this is equal to null foreach (T v in vec) tmp += v; return (tmp / vec.Length) as T; //mask to the Generic type }
Hope that helped Nassos"Success is the ability to go from one failure to another with no loss of enthusiasm." Winston Churchill "Quality means doing it right when no one is looking." Henry Ford