How to create a custom max() function without the ambiguity error.

realhet real_het at hotmail.com
Fri Dec 6 21:02:53 UTC 2019


On Friday, 6 December 2019 at 14:55:18 UTC, Ferhat Kurtulmuş 
wrote:
> On Friday, 6 December 2019 at 13:25:24 UTC, realhet wrote:
>> On Friday, 6 December 2019 at 13:04:57 UTC, Ferhat Kurtulmuş 
>> wrote:
>>> [...]
>>
>> Thx for answering!
>>
>> [...]
>
> In d you can also use scoped imports: 
> https://dlang.org/spec/module.html#scoped_imports

Yea, I know about that.
I also read the documentation about module imports, but in 
reality it feels like a bit different.

Here's my latest attempt on EXTENDING std.algorithm.max's 
functionality with a max operation on a custom type.
The type is the GLSL vec2 type which does the max operation 
component-wise.
The D std implementation uses the < operator, but with overriding 
that for my custom type it is impossible to realise. -> 
max(vec2(1, 2), vec2(2,1)) == vec2(2,2)

//So here is my helper module:
-----------------------------------------------------
module testimport_a;

import std.algorithm;

struct vec2{ float x, y; }

auto max(in vec2 a, in vec2 b){
   return vec2(max(a.x, b.x),
               max(a.y, b.y));
}

import std.algorithm: max;

// and the main module ////////////////////////////////

module testimport_main;

import std.stdio, testimport_a;

void main(){
   auto a = vec2(1, 2),
        b = vec2(0, 5);

   max(a, b).writeln;
   max(1, 2).writeln;
}

------------------------------------------------------

Both of the max instructions are working nicely.
But here are all the things/restrictions which aren't as nice:

- in the imported module it is really important, to put my max() 
function BEFORE the std one. The std implementation tries to 
serve EVERYTHING, but it fails the compilation when it check the 
< operator (which is non-existent on 2d vectors).

- It doesn't matter if I use public import or not. When it finds 
any compatible max() inside the helper unit's functions, and its 
imported functionst that are specified by name, it will compile 
it.

- It is really important to import the original max() by name. 
(After my narrower max())

- If I import std.algorithm in the main module, no matter the 
order, it will fail. As the std.algorithm.max alone is unable to 
serve vec2 types.

- I tried to make one more module, to be able to use max on vec2, 
vec3 and everything else, but I failed. none of the my random 
guessing worked.


More information about the Digitalmars-d-learn mailing list