ProtoObject and comparison for equality and ordering

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed May 15 09:39:00 UTC 2019


On Wednesday, May 15, 2019 2:56:53 AM MDT Steven Schveighoffer via 
Digitalmars-d wrote:
> On 5/14/19 9:36 PM, Eduard Staniloiu wrote:
> > Jonathan's question got us to the point raised: maybe it doesn't make
> > much sense to be able to compare two `ProtoObjects`, so maybe you
> > shouldn't be able to. This would change the interface to
> > ```
> > interface Ordered(T)
> > {
> >
> >      int opCmp(scope const T rhs);
> >
> > }
> > ```
> >
> > Now the attributes of `opCmp` will be inferred.
>
> Just wanted to make sure you understand this is not the case. opCmp in
> this instance is a virtual call, and will NOT have attributes inferred.
>
> There isn't really a way to define an interface for this, nor do you
> need to.
>
> Just define the opCmp you want in your own interface/base object, and
> then you can compare those. Almost nobody wants to compare 2 completely
> unrelated objects.

Indeed. Inference comes when the code around the member function is
templated. For instance, if you have phobos' RedBlackTree, it uses opCmp,
and it's templated. So, opCmp on the class can then have whatever attributes
are appropriate and the code in RedBlack that uses opCmp will infer those
attributes rather than forcing @safe or nothrow or whatever.

Similarly, with the free functions opEquals being templated, it would have
its attributes inferred based on how opEquals was defined on the classes
being compared, allowing == to be @safe, pure, etc. - or not - based on how
opEquals was declared on those classes, thereby allowing classes with an
@safe opEquals to be used in @safe code.

The functions on the class itself can only have their attributes inferred if
they're templated (which means that they can't be virtual), or they return
auto. So, in most cases, the attributes on these functions on classes
probably won't use inferrence, but the code that uses them will.

- Jonathan M Davis





More information about the Digitalmars-d mailing list