Why doesn't alias this work with arrays?
Jonathan M Davis
jmdavisProg at gmx.com
Mon Jun 18 09:55:51 PDT 2012
On Monday, June 18, 2012 18:51:01 Andrej Mitrovic wrote:
> struct Wrap
> {
> string wrap;
> alias wrap this;
> }
>
> void main()
> {
> Wrap x;
> x = "foo"; // ok
> Wrap[] y = ["foo", "bar"]; // fail
> }
>
> Error: cannot implicitly convert expression (["foo","bar"]) of type
> string[] to Wrap[]
>
> Any special reason why this doesn't work? I hope it's just a bug or
> unfinished implementation.
Generally, the type of the right-hand side of an assignment is determined
independently of the left-hand side. So, the type of ["foo", "bar"] would be
determined to be string[] before the compiler did anything with the left-hand
side. At that point, you'd need to be converting from string[] to Wrap[],
which would mean creating a new array, which isn't the sort of thing that
happens implicitly.
Now, there are a few exceptions.
ubyte[] a = [1, 2, 3, 4];
works even though [1, 2, 3, 4] is normally typed as int[], so the compiler
does adjust the type of the right-hand side under some circumstances, but it's
not the normal thing to do, which is probably why it's not working for you.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list