C++ Logo

std-discussion

Advanced search

Re: commutative functions

From: Matthew Woehlke <mwoehlke.floss_at_[hidden]>
Date: Wed, 2 Sep 2020 09:13:39 -0400
On 29/08/2020 20.03, Tobias W. via Std-Discussion wrote:
> This means, that I would have to write all those following functions,
> just to add them:
>
> Complex operator+ (Real a, Imag b);
> Complex operator+ (Imag b, Real a); // Mirrored function
> Complex operator+ (Real a, Complex b);
> Complex operator+ ( Complex b, Real a); //Mirrored function
> Complex operator+ (Imag a, Complex b);
> Complex operator+ ( Complex b, Imag a); //Mirrored function
>
> From a mathematical point of view, all mirrored functions are obsolete,
> because the intent has already been stated in the function above.
> Furthermore, each mirrored function will use additional program memory
> and this can become an issue on embedded devices.

At least the last problem can be solved, if your compiler is any good, like:

   inline Complex operator+(Imag b, Real a) { return a + b; }

Moreover, with appropriate use of concepts or enable_if, you could write:

   template <typename A, typename B>
   // not shown: ensure A, B are in {Real, Imag, Complex}
   inline Complex operator+(A a, B b) { return b + a; }

...and then add some specializations.

Would it be worthwhile to have a way to "automate" this better? Maybe.

Of course, in the example above, it may make more sense to allow Real
and Imag to promote to Complex and only supply:

   Complex operator+(Complex, Complex);

-- 
Matthew

Received on 2020-09-02 08:17:09