Possible D2 solution to the upcasting array problem, and a related
Luther Tychonievich
lat7h at virginia.edu
Fri Jan 2 17:21:31 PST 2009
Stewart Gordon Wrote:
> That leaves AAs to consider....
I can't find any conceptual difference here between any type of indirection: pointers, "ref" variables, static arrays, dynamic arrays, associative arrays, even aggregate types if the typing engine bothered with them:
void main(string[] args) {
const(int)[string] answers = ["L,tU,&E":42]; // AA
void refAA(ref const(int)[string] arg) { arg = answers; } // ref of AA
int[string] tmp = ["junk":0];
int[string]* arrayPointer = &tmp; // pointer to AA
refAA(*arrayPointer); // TODO: ban this cast
(*arrayPointer)["L,tU,&E"] = 43; // reassignment
writeln(answers); // check that it changed
}
I'd generalize your proposed rule 2:
> 2. If U is an upcast of T, then a legal implicit conversion is any of:
> (a) T[] to const(U)[]
> (b) T* to const(U)*
> (c) invariant(T)[] to invariant(U)[]
> (d) invariant(T)* to invariant(U)*
> Any other conversion from T[] to U[] or T* to U* is illegal.
with the more general:
2. If U is an upcast of T, then a legal implicit conversion is any of:
(a) indirect(T) to indirect(const(U))
(b) indirect(invariant(T)) to indirect(invariant(U))
where indirect is any type of array, pointer, or "ref" type. Ref is a little strange because it only shows up on the "to" side, being implicit on the "from" side.
Associative arrays are conceptually aggregates of two types (key and value), and both should follow the safe upcasting rules; in practice, however, the implementation (at least dmd 2.022) automatically const-s all but the outermost level of indirection within the key type, such that "int[int[]]" parses as "int[const(int)[]]", so the rule will never rule out a key type.
(incidentally, I just noticed that the AA initializer expression "[[1]:2]" won't parse in dmd...)
There may be some subtleties to the "all objects are implicitly pointers" rule (implying that class types are a kind of indirection), but at first glance they seem to be avoided because const-ness cannot get inside that implicit pointer.
More information about the Digitalmars-d
mailing list