On Monday, 13 July 2015 at 09:13:06 UTC, Yuxuan Shui wrote:
On Monday, 13 July 2015 at 09:10:41 UTC, ketmar wrote:
On Mon, 13 Jul 2015 06:49:09 +0000, Yuxuan Shui wrote:

The main reason here is to use '==' in @safe code:

class A {
        override @safe bool opEquals(Object o) {
                return cast(A)o !is null;
        }
}
@safe void main() {
        A a = new A;
        A b = new A;
        a == b;
}

This doesn't compile in current D, because objects.opEquals takes two Object, and Object.opEquals is not @safe.

Why can't we have a template objects.opEquals?

auto opEquals(T, S)(T a, S b) { ... }

'case templates can't be virtual functions, so the following will not work:

  bool cmp (Object a, Object b) { return a.opQeuals(b); }

  MyObj a, b;

  cmp(a, b);

What do you mean by virtual function? objects.opEquals is not a member function.

Currently, Object has a function named opEquals which _is_ a member function, and it is largely the reason, why opEquals on classes cannot be @safe - or pure, or nothrow - or even technically, const (though there's a hack in the free function, opEquals which casts away const to make const Objects comparable, which is a pretty dangerous thing to do in reality). Now, there is a free function called opEquals that calls the opEquals on a class object, and as I described in another post in this thread, it's supposed to be templatized at some point, but templatizing wouldn't allow you to have == be @safe, pure, or nothrow. For that to work, opEquals on the class itself must have those attributes, and to do that, opEquals needs to be removed from Object (as I described in that other post).

- Jonathan M Davis

Reply via email to