I have two classes that are a special kind of numeric value. Let me call one "value" and "fraction"; A fraction consists of a numerator and a denominator of type Value. Since these are numerical values, operator overloading (+ - * /) makes a lot of sense. Given the nature of the value, division returns a fraction. Operations can be performed using a combination of values โโand fractions.
Currently, I just defined an implicit transfer operator from Value to Fraction (and explicit from Fraction to Value, although I don't use it), and I don't use any inheritance.
I am wondering if there is any โelegantโ way to define both in terms of the abstract base class, which defines the set of available operations, and invokes the corresponding operation. Efficiency is a problem. I would prefer to use Fraction only when necessary, and it would not be necessary to define more complex operations for both cases separately, if they can be expressed using the same syntax.
One way that I see is to do something like the following for each operation, but I wonder if there are any more efficient ways to do this?
public static AbstractValue operator *(AbstractValue a, AbstractValue b) { Value valA = a as Value; Value valB = b as Value; if(valA == null) { Fraction fractA = a as Fraction; if(valB == null) { Fraction fractB = b as Fraction; return fractA * fractB; } return fractA * valB; } if(valB == null) { Fraction fractB = b as Fraction; return valA * fractB; } return valA * valB; }
lgaud
source share