www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Comparable Type

reply saotome <saotome.ran googlemail.com> writes:
Hi,

can someone tell me how can i check whether a type is comparable ? Is there
something like "IComparable" in C# ?
Dec 11 2008
next sibling parent Lars Ivar Igesund <larsivar igesund.net> writes:
saotome wrote:

 Hi,
 
 can someone tell me how can i check whether a type is comparable ? Is
 there something like "IComparable" in C# ?

Unfortunately not - the relevant operators are defined in opCmp, so they will always be implemented, even if the implementation may not be sane. -- Lars Ivar Igesund blog at http://larsivi.net DSource, #d.tango & #D: larsivi Dancing the Tango
Dec 11 2008
prev sibling parent "Jarrett Billingsley" <jarrett.billingsley gmail.com> writes:
On Thu, Dec 11, 2008 at 4:05 PM, saotome <saotome.ran googlemail.com> 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 :)
Dec 11 2008