I remember reading about generic type constraints in C# and I would swear there was a way to constrain some generic type T
using operator requirements, for example:
public class Matrix<T> where T has +, - defined for T and *, / defined for double
{
public Matrix(int rows, int columns)
=> (Rows, Columns) = (rows, columns);
public int Rows { get; set; }
public int Columns { get; set; }
...
public static Matrix<T> operator +(Matrix<T> m, Matrix<T> n)
{
if (m.Rows == n.Rows && m.Columns == n.Columns)
{
var matrixSum = new Matrix<T>(m.Rows, m.Columns);
// Write logic for matrixSum[i, j] = m[i, j] + n[i, j]
return matrixSum;
}
return null;
}
public static Matrix<T> operator *(double s, Matrix<T> m)
{
if (m is not null)
{
var scaledMatrix = new Matrix<T>(m.Rows, m.Columns);
// Write logic for scaledMatrix[i, j] = s * m[i, j]
return scaledMatrix;
}
return null;
}
public static Matrix<T> operator *(Matrix<T> m, double s) => s * m;
public static Matrix<T> operator /(Matrix<T> m, double s) => (1 / s) * m;
...
}
I'd like to keep the implementation as generally applicable as possible, so that T
could be a numeric type but also any custom type to do linear algebra with, for example complex numbers for which summation and scaling is defined.
Is it possible to have operator constraints like this on a generic type?