Problem with using std.math: abs and std.complex: abs at the same time

Simen Kjærås simen.kjaras at gmail.com
Thu Sep 19 11:16:12 UTC 2019


On Thursday, 19 September 2019 at 10:25:01 UTC, berni wrote:
> On Thursday, 19 September 2019 at 07:26:17 UTC, Simen Kjærås 
> wrote:
>> That does indeed fail to compile, and there's no easy way to 
>> introduce the module-level abs() function to the scope. Again 
>> though, MergeOverloads to the rescue:
>
> I'm not sure, if MergeOverloads will be accepted into 
> std/math.d. Meanwhile I've created a pull request (#7187), that 
> does not handle complex numbers although the algorithm would be 
> identical. Maybe handling complex numbers in math.d can be 
> added later (or maybe it's better to put this in std/complex.d 
> anyway, but then code duplication would be necessary).

You could perfectly well place MergeOverloads inside whatever 
function you make, thus not polluting std.math:

float abs(float f) {
     return f < 0 ? -f : f;
}

unittest {
     import std.complex : complex, cabs = abs;
     template MergeOverloads(T...) {
         static foreach (E; T)
             alias MergeOverloads = E;
     }
     alias abs = MergeOverloads!(cabs, .abs);
     abs(1);
     abs(complex(1,1));
}

(you can also use this to create ridiculous overload sets, since 
MergeOverloads doesn't care if one function is called abs and the 
other dropBackExactly. Please don't do this)

If you want to introduce MergeOverloads to Phobos officially, 
std.math is definitely *not* the place though. :)

I'd probably say std.functional, but I'm not really sure where 
it'd belong. Let's put it in std.exception, since it's an 
exception from D's usual overload rules in functions. :p

I don't think anything in std.math explicitly deals with 
std.complex at this point (some things may handle it 
generically), so it seems std.complex would be the logical place 
for anything that does. Might I ask what specifically you're 
working on?

--
   Simen


More information about the Digitalmars-d-learn mailing list