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

realhet real_het at hotmail.com
Fri Dec 6 13:25:24 UTC 2019


On Friday, 6 December 2019 at 13:04:57 UTC, Ferhat Kurtulmuş 
wrote:
> On Friday, 6 December 2019 at 12:34:17 UTC, realhet wrote:
>> Hi,
>>
>> I'm trying to use a popular function name "max", and extend it 
>> for my special types:
>>
>> For example:
>>
>> module utils;
>> MyType max(in MyType a, in MyType a){...}  //static function
>>
>> struct V3f{
>>   V3f max(in V2f b){...} //member function
>> }
>>
>> module gl3n;
>> vec3 max(in vec3 a, in vec3 a) //another static function in 
>> different module
>>
>> I also want to use std.algorithm.comparison.max as well.
>>
>>
>> I know that the ambiguity error can be avoided by public 
>> importing all the various max implementations into one place, 
>> but how to do this when I want to use 3 modules? Need a 4th 
>> module to combine them all? Is there a nicer way?
>> Another question that is it possible to extend the the 
>> template function "to" in more than one module and use it 
>> easily from my main project modules?
>
> how about this:
>
> import std.stdio;
> import std.algorithm.comparison: max1 = max;
>
> int max(int a, int b){ // dummy max
>     return 5;
> }
>
>
> void main(){
>     int a = 2;
>     int b = 3;
>
>     max1(a, b).writeln; // writes 3
>
> }

Thx for answering!

This is what I want to avoid: To use extra identifiers or imports 
for the same semantic task.

------------------------
module m1;
public import std.algorithm.comparison: max;
struct MyType{ int x;}
MyType max(in MyType a, in MyType a){ return a.x>b.x ? a : b; }


module main;
import m1;

------------------------
 From here: the max() is working for MyType and also for the types 
supported by std.algo.comparison.max.

BUT! What if I want to import another module which is overloading 
max?! It will be an ambiguity between m1 and the other module.
I'm searching for a clever solution, not just manually 
reimporting everything in every module where I use multiple 
modules which also manually reimporting those simple names like 
'max'.



More information about the Digitalmars-d-learn mailing list