It seems to me that it is not only my problem.
Please do not close my question as a duplicate because I looked these questions through and I did not find the solution.
class Matrix<T> {
private Int32 rows;
private Int32 cols;
private T[,] matrix;
public Matrix() {
rows = cols = 0;
matrix = null;
}
public Matrix(Int32 m, Int32 n) {
rows = m;
cols = n;
matrix = new T[m, n];
}
public T this[Int32 i, Int32 j] {
get {
if (i < rows && j < cols)
return matrix[i, j];
else
throw new ArgumentOutOfRangeException();
}
protected set {
if (i < rows && j < cols)
matrix[i, j] = value;
else
throw new ArgumentOutOfRangeException();
}
}
public Int32 Rows {
get { return rows; }
}
public Int32 Cols {
get { return cols; }
}
public static Matrix<T> operator+(Matrix<T> a, Matrix<T> b) {
if(a.cols == b.cols && a.rows == b.rows) {
Matrix<T> result = new Matrix<T>(a.rows, a.cols);
for (Int32 i = 0; i < result.rows; ++i)
for (Int32 j = 0; j < result.cols; ++j)
result[i, j] = a[i, j] + b[i, j];
return result;
}
else
throw new ArgumentException("Matrixes don`t match operator+ requirements!");
}
public static Matrix<T> operator-(Matrix<T> a, Matrix<T> b) {
if (a.cols == b.cols && a.rows == b.rows) {
Matrix<T> result = new Matrix<T>(a.rows, a.cols);
for (Int32 i = 0; i < result.rows; ++i)
for (Int32 j = 0; j < result.cols; ++j)
result[i, j] = a[i, j] - b[i, j];
return result;
}
else
throw new ArgumentException("Matrixes don`t match operator- requirements!");
}
You know what the compiler tells: "Operator '-' cannot be applied to operands of type 'T' and 'T'", that is for all operators.
So, what`s the best decision for this? As far as I know, interfaces can not contain operators, so the only way is abstract base class for the type T. but also, as I discovered, operatoes can not be defined as abstract.