jacobnavia <
ja...@jacob.remcomp.fr> wrote:
> When doing operator overloading for some new type of number, there is a
> LOT of overloads to be done, one for each operator you want to overload,
> but also for each operation twice...
>
> For instance:
>
> T operator +(T arg1, double arg2);
>
> Then you handle
>
> T t;
> t = t+2.9;
>
> OK, but what about
> T operator +(double arg1, T arg2);
>
> That handles 2.9+t.
>
> Is that really necessary? Isn't addition commutative?
The problem isn't if it's commutative or not. The problem is that if the
operands are of different types, whether you want to support specifying
them in either order. If you want to support things like:
MyClass obj1, obj2;
obj1 = obj2 + 10;
obj1 = 10 + obj2;
obj1 = obj2 - 10;
obj1 = 10 - obj2;
there are four overloads there that need to be written (especially if you
don't want an integer to implicitly convert to an object of type MyClass).
I remember years ago where I was in a situation where I needed a function
to take three parameters. Any of the three parameters could be one of two
types (which weren't implicitly convertible between each other). That's like
an exponential number of overloads.
I don't think there's a perfect solution for this. You could just template
all the parameters (or, in modern C++, make them auto), but making a
function templated can be highly problematic (as the implementation now
needs to be available where the function is called) and the types being
completely free can also cause problems and, at a very minimum, obscure
error messages if they are of the wrong type (although I think C++20 gives
tools to make this much better).
You could also create some kind of "proxy" type that contains some kind
of reference to the original values, but that can be problematic too.
Also probably adds a level of inefficiency.