alias this/opGet and opCast conversion
anonymous
anonymous at example.com
Mon Dec 17 07:46:20 PST 2012
On Monday, 17 December 2012 at 15:10:24 UTC, js.mdnq wrote:
> This i probably a rather dumb question but I've been up all
> night and therefor have a really good excuse ;) (I can barely
> see straight...)
>
>
> Is opGet the reverse opAssign? I can't find any docs on it but
> it does let me write converters from my type to another type.
>
> e.g.,
>
> struct X { int value; }
>
> double x = xX;
>
> without an opGet or alias this I get an error about not being
> able to implicitly convert. Using alias this solves the
> problem. Using opGet seems to let me write a converter(which I
> can't seem to do otherwise).
>
> For example, it seems I could use opGet to normalize X's value
> when converting to a double.
>
> That is, the way I see it is
>
> double x = xX;
>
> The compiler checks to see if double has an opAssign that will
> convert X to a double. If not it checks if X has an opGet
> call(a sort of reverse opAssign).
>
> Is this the correct understanding of opGet or is there more too
> it.
>
> What if I have
>
> struct X { int value; X opAssign(Y y); }
> struct Y { double value; X opGet(); alias opGet this; }
"opGet" is not a special name. The magic comes from alias this.
You can use another name just fine.
>
> then
>
> X x; Y y;
>
> what does
>
> x = y;
> y = x;
>
> do?
>
> It seems the first will call X's opAssign and Y's opGet unless
> there is precedence?
I guess opAssign wins, because alias this is only considered if
it doesn't work out with the original type.
> y = x will fail with the implicit conversion error?
Yes, assigning x directly to y doesn't work, and assigning it to
y.opGet (via alias this) doesn't work either, so it fails.
More information about the Digitalmars-d-learn
mailing list