Operator overloading makes numerical code much more readable than method calls. It would be nice if we could define operators that acted on interfaces in C#:
For example:
interface IMatrix{
double this[int row, int column] { get; set; }
Matrix Add( Matrix other);
...
}
then define:
static IMatrix operator+ (IMatrix a, IMatrix b){
return a.Add(b);
}
The problem is that C# doesn't allow global methods (methods defined outside of a class) or static methods in an interface. This would work if IMatrix was an abstract class, but not as interface.
C++ allows global methods, would this work in C++/CLI?
public interface class IMatrix
{
public:
property
double default[int,
int] {
double get
(int row,
int column
);
void set
(int row,
int column,
double value
);
}
IMatrix^ Add
(IMatrix^ other
);
...
};
IMatrix^ operator + (IMatrix^ a, IMatrix^ b){
return a->Add(b);
}
int main(array<System::String ^> ^args){
IMatrix^ a = gcnew Matrix(3,3);
IMatrix^ b = gcnew Matrix(3,3);
IMatrix^ c = a+b;
return 0;
}
Yep it compiles with /clr:safe (no CLS compliant warnings) and runs. Cool, can we now call this from C#? Nope. The problems is that CSC will not compile line 3:
IMatrix a = new Matrix(3, 3);
IMatrix b = new Matrix(3, 3);
IMatrix c = a + b;
error: Operator '+' cannot be applied to operands of type 'IMatrix' and 'IMatrix'.
I wonder why this is. The DLL generated by C++/CLI contains the overloaded operator method.
Oh well, guess we cannot go this route.