max() in phobos?

Reiner Pope reiner.pope at REMOVE.THIS.gmail.com
Mon Nov 13 22:55:28 PST 2006


Sean Kelly wrote:
> Bill Baxter wrote:
>> Is there a generic 'max' function anywhere in phobos?
>> The closest I could find was std.math.fmax().
> 
> Not that works for all input types, as far as I know.  However, 
> something like the code below should work.  This is off the top of my 
> head so it may have bugs, but it's a general idea of what such a 
> template function may need to do.
> 
> /**
>  * Returns the largest of the two supplied types, or the first type if
>  * the sizes are identical.  If either type is an object then both must
>  * be objects of either the same type or where one is a base class of
>  * the other.  Interfaces are not supported.
>  */
> template largestOrConvertible( T, U )
> {
>     static if( is( T : Object ) || is( U : Object ) )
>     {
>         static assert( is( T : Object ) && is( U : Object ),
>                        "Types incompatible." );
> 
>         static if( T : U )
>             alias T largestOrConvertible;
>         else static if( U : T )
>             alias U largestOrConvertible;
>         else static assert( false, "Object types must be related." );
>     }
>     else static if( is( T : Interface ) || is( U : Interface ) )
>         static assert( false, "Interface types not yet supported." );
>     else static if( T.sizeof < U.sizeof )
>         alias U largestOf;  // concrete type, U larger
>     else alias T largestOf; // concrete type, T larger or equal
> }
> 
> template max( T, U )
> {
>     largestOrConvertible!(T,U) max( T t, U u )
>     {
>         return t > u ? t : u;
>     }
> }
> 
> template min( T, U )
> {
>     largestOrConvertible!(T,U) min( T t, U u )
>     {
>         return t < u ? t : u;
>     }
> }
We could do all of this code, or we could just have type inference for 
return values:

auto max (T, U) (T t, U u)
{
   return t > u ? t : u;
}

Problem solved!



More information about the Digitalmars-d-learn mailing list