Here I have a minimal example of a class that should model a vector (to be used for linear algebra computations). It includes a type T
that will be an integral or floating point type (like for instance int
or double
). Now I wanted to implement a method CheckIfZeroAt
that checks whether a certain entry contains a zero or not. The problem is that I want to leave the type T
variable, but as far as I know I have no way to tell the compiler that I T
is a numeric type where the typecast is available. Unfortunately there also does not seem to be an interface for numeric types that I could restrict T
to.
Is there any elegant way to solve this problem?
I included a few naive ways one could try to implement this method as comments, but none of them work.
class MyVector<T> // T is an integral or floating point type
{
T[] vector;
public MyVector(T[] array)
{
vector = array; //just a reference
}
public bool CheckIfZeroAt(int i)
{
// return vector[0] == (T)0; //"Cast is redundant"
// return vector[0] == 0; // Operator "==" cannot be applied to operands of type "T" and "int"
// return vector[0] == 2 * vector[0]; // Operator "*" cannot be applied to operands of type "T" and "int"
}
}