Some problems with operator overloading

bearophile bearophileHUGS at lycos.com
Mon Mar 15 07:46:01 PDT 2010


Steven Schveighoffer:

>I think there is no restriction on what opEquals in structs.<

I think this is a hole in the specification that needs to be filled, because I think you must be sure opEquals returns a bool.


>These kinds of errors are appropriate for a lint tool.<

Have you seen any good lint tool for D?

Generally any compiler error can be moved to a lint tool, so it's a matter of balance. In my opinion generally if some sanity test on the code is computationally heavy or the errors it spots are uncommon, or if it's not certain they are really errors, or if it's very uncommon, then it's possible or better to move it to a lint. If the test is not hard/heavy to do and it can catch a common sure mistake then it's better to put it into the compiler. D compiler already performs several tests that were work for C lint tools. 

So I think the compiler can be allowed to catch some potentially common operator overloading bugs like opBinary("==").


>Note that opBinary can be directly called via: myfoo.opBinary!("0")(other);<

And that's insane code, right. Today programmers want a nanny compiler that helps. The age of strong silent C compilers is dead or it's acceptable for kernel devs only.


>This is a bug, I think introduced by a recent change that makes f++ an lvalue.  Please file a bugzilla report.<

OK.


>opImplicitCast was abandoned for the more versatile alias this.<

I fear that "alias this" sometimes can be a little too much versatile for the programmer own good :o)


> Something like this should work:
> struct Foo {
>    int x;
>    int opCast(T:int)() { return this.x; };
>    alias opCast this;
> }

This little program:

struct Foo {
   int x;
   uint opCast(T:uint)() { return this.x; }
   int opCast(T:int)() { return this.x; }
   alias opCast this;
}
void main() {
    Foo f = Foo(5);
    int[] a = new int[f]; // line 9
}


Gives the following errors:
test.d(9): Error: cannot implicitly convert expression (f) of type Foo to uint
test.d(9): Error: cannot cast f.opCast(T : int)

--------------------

Trass3r:

>Seconded. The language specification is clear about that. == is not to be used with opBinary.<

The specifications can be clear about all things, but one of the purposes of the compiler is to help catch programmer errors too. If you don't agree then please remove all error messages and safeties from the compilers you use and have fun programming.

Thank you for your answers and comments,
bearophile



More information about the Digitalmars-d mailing list