Array initialization with common base - Best way?

"Jérôme M. Berger" jeberger at free.fr
Sun Nov 9 02:37:06 PST 2008


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

deadimp wrote:
> What's a 'good' way to initialize an array of references to classes using a common base?
> I've tried this and it works:
> 
> class Base
> {
>  void func();
> }
> class GoodChild : Base
> {
>  void func();
> }
> class BadChild : Base
> {
>  void func();
> }
> //...
> auto list = [cast(Base)new GoodChild, new BadChild, ...];
> 
> I had tried doing it without the initial cast, but ran into issues because D (DMD v1.033) would infer the type based off of the first element in the literal, and then assumed that all other elements would be the same. 

	I would replace the last line with:
Base[] list = [ new GoodChild, new BadChild, ...];

	It's clearer, there's less typing and it won't suddenly fail if you
remove the first element and accidentally remove the cast at the
same time or if you add a new first element and forget to add the
cast...

		Jerome
- --
+------------------------- Jerome M. BERGER ---------------------+
|    mailto:jeberger at free.fr      | ICQ:    238062172            |
|    http://jeberger.free.fr/     | Jabber: jeberger at jabber.fr   |
+---------------------------------+------------------------------+
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEARECAAYFAkkWvUEACgkQd0kWM4JG3k/+lQCfTvFvrT5CmEhC0z5r11Esj5Cv
IckAn1csTb5QyDZr2icXHfDKqYDMKC0w
=SXsh
-----END PGP SIGNATURE-----


More information about the Digitalmars-d-learn mailing list