On 7/20/21 11:49 AM, H. S. Teoh wrote:

> On Tue, Jul 20, 2021 at 11:32:26AM -0700, Ali Çehreli via Digitalmars-d-learn wrote:
>> On 7/19/21 11:20 PM, Tejas wrote:
>>
>>> trying to create the spaceship operator of C++
>>
>> Just to make sure, D's opCmp returns an int. That new C++ operator was
>> added to provide the same semantics.
> [...]
>
> FYI, opCmp *may* return float, which may be useful sometimes for
> implementing partial orders (return float.nan when two elements are
> incomparable).

Thanks. For that matter, opCmp can return a UDT (and bool as well as demonstarted below) but then the UDT cannot know what to do in its opCmp: :)

import std.stdio;

void main() {
  S a, b;
  auto result = a < b;
  // The operator above is reduced to the following:
  //
  //   a.opCmp(b) < 0;
  //
  // (It would be 'a.opCmp(b) >= 0' if we used the >= operator, etc.)
  //
  // But because the result of opCmp is an O object in this code
  // (let's call it 'o'), the reduction is applied to 'o < 0' as well:
  //
  //   o.opCmp(0);
  //
  // where, O.opCmp will receive a 0 'int' value but will never know
  // operator context we are in. (<, >=, etc.)
}

struct S {
  // Weirdly returns an O.
  O opCmp(const S that) {
    return O();
  }
}

struct O {
  bool opCmp(int result) {
    // result will always be '0' in the case of reduction because it
    // will be the 0 used in code reduction by dmd.

    // We might be able to do something here but we don't know the
    // operator context. Are we inside <, >=, etc?

    // Extra credit: This is similar to being able to return float.nan
    // but I can't decipher the semantics at this time. :)
    return true;
  }
}

Ali


Reply via email to