User-defined "opIs"

Marco Leise via Digitalmars-d digitalmars-d at puremagic.com
Mon Sep 29 03:12:13 PDT 2014


Am Sun, 28 Sep 2014 14:43:03 +0000
schrieb "Marc Schütz" <schuetzm at gmx.net>:

> Yeah, it wasn't a good idea. Somehow it felt strange to throw all 
> type safety out of the window, but on the other hand, bit-level 
> comparison is the purpose of `is`, which isn't typesafe to begin 
> with.

I have the same feeling. No matter how we do it, one of the
comparisons will always be left behind:

1a) identity of references with same referred type
  - objects with same reference and common inheritance branch
  - static arrays and the full slice over them
  - pointers of same type
1b) reference identity after implicit casts per language rules
  - void* with reference type
  - void[] with typed array
2) raw bit level equality (includes 1a) and parts of 1b))
  - proxy struct with wrapped type
  - signed with unsigned types on the bit level
3a) logical / overridable equality for user defined types
  - comparison of uint.max with -1 results in false
  - safe type widening 1.0f with 1.0, -1 with -1L, char types
  - opEquals()
3b) 3a) with "C-style" equality for built-in types
  - equal after integer type promotion
  - equal after implicit cast

One can define these from other perspectives, and the bit-wise
struct comparison may be seen as a default opEquals (which I
do here) or as a raw bit equality.

"==" is doing 3b). "is" comprises 1a), 1b) and 3b) as a
fallback to be defined for all types.
Defining "is" as 2) would remove the overlap for both
operators in 3b), but loose type-safety in 1a+b) and disallow
comparison of `void[] is ulong[]` since their lengths
will differ even if they span the same memory area.

With two operators we can capture any two subsets which
sound logical on their own, but not all of the possible
notions of identity and equality. And since people already
wonder about "is" in D and "===" in JavaScript it is probably
not a good idea to add even more comparison operators.
So I conclude that we will have to live with that shortcoming.

-- 
Marco



More information about the Digitalmars-d mailing list