On 4/4/20 8:45 AM, Steven Schveighoffer wrote:

>> Yes, sure, but in C++ I don't have to explicitly write this down. It
>> just works. IMO that makes a lot of sense as long as all types fit.
>> This just looks superfluously.
>>
>
> steves@homebuild:~$ cat test.cpp
> struct S
> {
>      float a;
>      float b;
> };
> int main()
> {
>      S a = {1, 5};
>      S b = {2, 5};
>
>      a += b;
> }
> steves@homebuild:~$ g++ -o test test.cpp
> test.cpp: In function ‘int main()’:
> test.cpp:11:4: error: no match for ‘operator+=’ (operand types are ‘S’
> and ‘S’)
>    a += b;
>    ~~^~~~
>
> Doesn't seem to "just work" for me...

I was about to say the same. C++ does not have this feature. What it has as a feature and as a guideline is to define an operator+ outside of the type's definition. Perhaps that's what's helping in C++ in this case: the type looks clean but there are "interface" functions outside of it.

I've used the following trick in D for many of my types, which I've been copy-pasting but it can be mixed in:

struct S {
  float a;
  float b;

  int opCmp(const(typeof(this)) that) const {
    import std.typecons : tuple;
    return tuple(this.tupleof).opCmp(tuple(that.tupleof));
  }
}

unittest {
  assert(S(3) < S(4));
  assert(S(1, 2) > S(1, 1));
}

void main() {
}

Ali


Reply via email to