On Thu, Dec 11, 2008 at 4:05 PM, saotome <[email protected]> wrote:
> Hi,
>
> can someone tell me how can i check whether a type is comparable ? Is there 
> something like "IComparable" in C# ?

It's not entirely a replacement, but you can use some static checking
to make sure that comparison between two types makes sense using is()
and typeof():

int cmp3(T, U)(T a, U b)
{
        // is(typeof(a < b)) will only evaluate 'true' if a can be compared to b
        static assert(is(typeof(a < b)), "ack, can't compare types '" ~
                T.stringof ~ "' and '" ~ U.stringof ~ "'");

        if(a < b)
                return -1;
        else if(a > b)
                return 1;
        else
                return 0;
}

void main()
{
        cmp3(3, 4); // fine
        cmp3(3, "hello"); // compilation failure
}

However, if you have two Object references and want to see if they're
comparable to one another (i.e. by seeing if they are both instances
of IComparable<Foo> in C#), you're probably out of luck.  Thankfully,
most of the time you shouldn't be dealing with Object references
anyway.  That's what templates are for :)

Reply via email to