digitalmars.D.learn - Comparable Type
- saotome (2/2) Dec 11 2008 Hi,
- Lars Ivar Igesund (7/11) Dec 11 2008 Unfortunately not - the relevant operators are defined in opCmp, so they...
- Jarrett Billingsley (26/28) Dec 11 2008 It's not entirely a replacement, but you can use some static checking
Hi, can someone tell me how can i check whether a type is comparable ? Is there
Dec 11 2008
saotome wrote:Hi, can someone tell me how can i check whether a type is comparable ? IsUnfortunately 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
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 thereIt'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 most of the time you shouldn't be dealing with Object references anyway. That's what templates are for :)
Dec 11 2008