max() in phobos, and English logic operators

Sean Kelly sean at f4.ca
Wed Nov 8 15:48:02 PST 2006


Bill Baxter wrote:
> 
> Especially annoying for containers parameterized by numeric type. Then 
> you don't know what to use for the literal you're comparing against, so 
> you've got to use a cast.
> 
>    T x = 17;  // could be float,double,real,int etc
>    std::max(x, cast(T)0); // ugh.

In all fairness, this can be rewritten as:

     std::max<T>( x, 0 );

By the way, I had to add casts to my min/max functions to allow class 
types to be comparable.  For example:

     class A
     {
       int opCmp( A rhs )      { ... }
       int opCmp( Object rhs ) { ... }
     }
     class B : A {}
     class C : A {}

     A a = new A;
     B b = new B;
     C c = new C;

     min( a, b ); // 1
     min( b, a ); // 2
     min( b, c ); // 3

In cases 1 and 2, opCmp(A) should be called, but the call is ambiguous 
since b is convertible to both A and Object.  And in case 3, 
opCmp(Object) should be called, since the mechanism isn't smart enough 
to figure out that b and c have a common user-defined parent.  Casting 
fixes both of these, though it pained me to add it :-)

Sean



More information about the Digitalmars-d-learn mailing list