Array of interfaces static initialization
Steven Schveighoffer
schveiguy at yahoo.com
Fri Apr 18 11:38:54 PDT 2008
"Yossarian" wrote
> Hello.
> I've got following array:
>
> typedef iObject[] paramList;
>
> and following object architecture:
>
> abstract class iObject { ... };
> class associativeArray : iObject { ... };
> class block : iObject { ... };
> class cIrc : block { ... };
> class command : associativeArray { ... };
>
> and have function
> Run(paramList);
>
> ..
>
> when I use (z.B.)
>
> command c;
> cIrc this;
>
> Run([c, this]);
>
> irc.d(278): Error: cannot implicitly convert expression (this) of type
> ghhd.irc.
> cIrc to ghhd.irc.command
>
> both command and irc could be easily upcast to iObject,
> so I think that this is absolutely legal usage (bug ?), or I've badly
> understood the array initializer?
>
Not so badly :) Basically, the expression [c, this] is ambiguous to the
compiler. So it makes a decision and says whatever the type of the first
element is the type of the array. So it types this as command[2]. Then it
can't implicitly convert cIrc to command automatically so it pukes.
Janice's solution tells the compiler how to declare the literal (as an
iObject[])
What you don't realize is that the D language is structured to have
context-free parsing, which means just because [c, this] is used as an
argument to Run, which takes iObject[], doesn't matter. The compiler looks
at [c, this] without context and tries to determine the type just from those
tokens. This makes the compiler implementation much simpler, but makes the
compiler less 'intuitive.'
-Steve
More information about the Digitalmars-d
mailing list