Two problems with op overload

Robert Clipsham robert at octarineparrot.com
Sun Mar 14 07:44:53 PDT 2010


On 14/03/10 13:14, bearophile wrote:
> I have tried to use the new operators of D2 and I have found several problems. This small program shows two of those problems (some of my problems can be caused by my improper usage, I'm trying to tell apart the operator overloading bugs from my improper usage cases).
>
> Do you know if/how this program can be fixed?
>
>
> struct Foo {
>      int x;
>
>      Foo opUnary(string op:"++")() {
>          this.x++;
>          return this;
>      }
>
>      uint opCast(T:uint)() {
>          return this.x;
>      }
> }
>
> void main() {
>      Foo f = Foo(5);
>      f++; // line 16
>      auto a = new int[f]; // line 17
> }
>
> Errors:
> temp2.d(16): Error: var has no effect in expression (__tmp1)
> temp2.d(17): Error: cannot implicitly convert expression (f) of type Foo to uint
>
> Note: the line 17 works if I write it this way, but it's not nice:
> auto a = new int[cast(uint)f];
>
> Bye,
> bearophile

I don't know about your first problem, but the latter is because opCast 
is only for explicit casts. I think implicit casts can be emulated with 
alias this, eg:
----
alias x this;
----
I'm not sure though as I haven't tested it. This also means that 
anything that isn't defined in Foo will be forwarded to x though, which 
might not be what you want.


More information about the Digitalmars-d-learn mailing list