Skip to content

Commit d8fcb7e

Browse files
authored
[spec/operatoroverloading] Add class opEquals example (#4221)
1 parent 32738eb commit d8fcb7e

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

spec/operatoroverloading.dd

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -431,13 +431,30 @@ $(OL
431431
)
432432

433433
$(P If overriding $(D Object.opEquals()) for classes, the class member
434-
function signature should look like:)
434+
function should take an `Object` parameter and dynamically check
435+
that it is a compatible class, e.g.:)
436+
437+
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
435438
---
436439
class C
437440
{
438-
override bool opEquals(Object o) { ... }
441+
int i;
442+
443+
this(int i) { this.i = i; }
444+
445+
override bool opEquals(Object o)
446+
{
447+
if (auto c = cast(C) o)
448+
return c.i == i;
449+
else
450+
assert(0, __FUNCTION__ ~ ": Cannot compare a " ~ typeid(o).toString);
451+
}
439452
}
453+
454+
static assert(new C(2) == new C(2));
455+
static assert(new C(2) != new C(3));
440456
---
457+
)
441458

442459
$(P If structs declare an $(D opEquals) member function for the
443460
identity comparison, it could have several forms, such as:)
@@ -522,7 +539,10 @@ void main()
522539
}
523540
---
524541
$(P If overriding $(D Object.opCmp()) for classes, the class member
525-
function signature should look like:)
542+
function should take an `Object` parameter and dynamically check
543+
that it is a compatible class for the comparison (like when overriding
544+
$(RELATIVE_LINK2 equals, `opEquals`)).)
545+
526546
---
527547
class C
528548
{

0 commit comments

Comments
 (0)