views:

350

answers:

2

Not too practical maybe, but still interesting.

Having some abstract question on matrix multiplication I have quickly implemented a matrix for ints, then tested my assumptions.

And here I noticed that just int matrix is not good, if I occasionally want to use it with decimal or double. Of course, I could try just to cast all to double, but that's not convenient way.

Continue with assumption we could have a bunch of objects we are able to add and multiply - why don't use them in my matrix?

So, just after considering it would be a Matrix class now I faced that generic T could not be used, I need it to support some interface which could add and multiply.

And the problem is I could override operators in my class, but I could not introduce an interface which would support operators. And I have an operators in built-in types, but still no interface over them.

What would you do in such a case considering you do not want to duplicate worker class body? Wrappers and implicit casting didn't help me much, I'm interested in a beautiful solution.

Thanks.

+5  A: 

For this you need generic maths. Luckily I have done this. Usage would be similar to this "complex" (i.e. x+iy) example. The Operator class is now part of MiscUtil.

Marc Gravell
Typical... I see a post I can answer referencing your work, and you've got here first ;)
Jon Skeet
Well, I have to try and get *some* points - you're accelerating away too quickly ;-p
Marc Gravell
Thanks, that's a really cool idea and unexpected use of expressions :)
Ilya Komakhin
Yes; Expression is *incredibly* versatile; you can do all sorts of eccentric things with it, and cache the compiled delegate for efficient usage, but first you need to get your head around Expression - which isn't trivial.
Marc Gravell
+1  A: 

Well, there is a less tech-heavy way to do just that. You cannot add a new interface for "int" or "double". But you can declare an interface for an object that can multiply and add values of some generic type. And then you can implement the interface for all the types you need:

public interface ICalculator<T>
{

   T Add(T x, T y);
   T Multiply(T x, T y);

}

public class MatrixMultiplier<T>
{

  public MatrixMultiplier(ICalculator<T> calculator) { ... }

}

public class IntCalculator : ICalculator<int>
{

  public int Add(int x, int y)
  {
    return x + y;
  }

  public int Multiply(int x, int y)
  {
    return x * y;
  }

}
Orlangur