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

Mike Parker aldacron at
Fri Dec 6 22:14:10 UTC 2019

On Friday, 6 December 2019 at 21:02:53 UTC, realhet wrote:

> 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)

The reason you're having so much trouble with this is that you're 
violating the contract of max. It's a template, so it's already 
set up to work with custom types without any need to write a 
custom max function, as long as the types adhere to the contract.

Consider other functions in std.algorithm, such as sort or equal, 
that allow you to pass a custom predicate. max doesn't have that 
because, by defintion, there is only one comparison for it to do: 
 >. Any type that doesn't support that isn't going to work with 

Moreover, your return value violates the function's contract:

"Iterates the passed arguments and return the maximum value."

You aren't returning the maximum value. You're returning a new 
value constructed from the maximum components of the two 
parameters. That is not the same behavior as max(1, 3).

Given that your function has a different contract, it should also 
have a different name.

More information about the Digitalmars-d-learn mailing list