challenge: implement the max function

Sean Kelly sean at f4.ca
Mon Jan 22 12:04:09 PST 2007


Don Clugston wrote:
>
>     // Implicitly convert to the smallest type which can store both T 
> and U; acts like an 'auto' template return type.
> template SharedComparisonType(T, U) {
>     static if (is( typeof( (T x, U y){ return y<x? y: x;}) Q == return))
>         alias Q SharedComparisonType;
> }

Clever :-)  I suppose one parameter of this challenge should be some 
criteria for flexibility though.  For example, the above code doesn't 
work for this case:

     class B {}
     class C : B {}
     class D : B {}

     min( new C, new D );

And it perhaps should, since Object.opCmp(Object) exists.  Worse, if B 
is redefined as:

     class B { int opCmp( B val ) {} }

Then the overload mechanism can't determine whether to use Object.opCmp 
or B.opCmp for comparing C and D.

An added challenge would be to support:

     class B { int opCmp( int val ) {} }

     min( new B, 2 );

But perhaps all of this is going too far?  Your example is simple and 
handles the majority of realistic situations.


Sean



More information about the Digitalmars-d mailing list