Array initializers and inheritance
Chris Nicholson-Sauls
ibisbasenji at gmail.com
Sun Oct 29 21:00:15 PST 2006
Frank Benoit (keinfarbton) wrote:
> I think, the array initialization feature is not so nice. The array
> takes its type from the type of the first initializer. This is
> absolutely ugly.
You are correct that it takes its type from the first element. In the vast majority of
cases (personal experience, might not be general) this hasn't been a problem. Still, I do
feel a little antsy sometimes about putting that cast() at the beginning.
> I would prefer if you can write this
> _gameObjects = new GameObject [ new Player(), new Target(Direction.Up,
> 0, 0)];
If one uses the CashewUtils array library (cashew.utils.array, available from DSource)
then you can do:
# _gameObjects = array!(GameObject)(new Player, new Target(Direction.Up, 0, 0));
Still not perfeclty ideal, of course. This is my current personal (biased) preferance. ;)
> The second bad thing is, they tend to generate static arrays. So often
> you need to append a [] to convert the static array into a dynamic one.
As far as I know, this shouldn't be neccesary. If I remember right, static arrays
implicitly cast to dynamic arrays (but not the other way around). In fact, the extra []
at the end doesn't cast the array at all, but rather takes a full slice of it. Which
still has the desired effect, but...
> When generating D code, i use array initialization and cast every member
> to the type of the array element and append [] to every such
> initializer. This code looks really ugly.
You only have to cast the first one, as this is what determines the array's type.
-- Chris Nicholson-Sauls
More information about the Digitalmars-d-learn
mailing list